mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-08 02:04:31 +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);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user