mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-08 18:32:56 +08:00
Add ReverseWordsInString
(#4456)
* return a string of the words in reverse order concatenated by a single space. Input: s = "the sky is blue" Output: "blue is sky the" * return a string of the words in reverse order concatenated by a single space. Input: s = "the sky is blue" Output: "blue is sky the" * space reduce * removed main method * added test cases * formatting fix * formatting fix * worked on pr reviews * formatting fix * private constructor added * added test case for when string contains white space * simplified method * fix issue * formatting issues fix * fixed issue * code refactor * documented method * worked on pr comments * docs: add missing space * tests: express as `ParameterizedTest` --------- Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com> Co-authored-by: vil02 <vil02@o2.pl>
This commit is contained in:
@ -0,0 +1,22 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
|
||||
public final class ReverseWordsInString {
|
||||
|
||||
private ReverseWordsInString() {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Reverses words in the input string
|
||||
* @param s the input string
|
||||
* @return A string created by reversing the order of the words in {@code s}
|
||||
*/
|
||||
|
||||
public static String reverseWordsInString(final String s) {
|
||||
var words = s.trim().split("\\s+");
|
||||
Collections.reverse(Arrays.asList(words));
|
||||
return String.join(" ", words);
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.thealgorithms.strings;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
|
||||
public class ReverseWordsInStringTest {
|
||||
@ParameterizedTest
|
||||
@MethodSource("inputStream")
|
||||
void numberTests(String expected, String input) {
|
||||
Assertions.assertEquals(expected, ReverseWordsInString.reverseWordsInString(input));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> inputStream() {
|
||||
return Stream.of(Arguments.of("blue is Sky", "Sky is blue"), Arguments.of("blue is Sky", "Sky \n is \t \n blue "), Arguments.of("", ""), Arguments.of("", " "), Arguments.of("", "\t"));
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user