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:
Suchi Bansal
2023-10-06 23:45:27 +05:30
committed by GitHub
parent 064ca8f591
commit 081f308b9d
2 changed files with 42 additions and 0 deletions

View File

@ -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);
}
}

View File

@ -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"));
}
}