-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathReverseWordsInString.java
32 lines (24 loc) · 1.01 KB
/
ReverseWordsInString.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package array_string;
public class ReverseWordsInString {
public String reverseWords(String input) {
if (input == null || input.isEmpty()) {
return "";
}
String[] words = input.trim().split("\\s+");
StringBuilder reversedString = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversedString.append(words[i]);
if (i != 0) {
reversedString.append(" ");
}
}
return reversedString.toString();
}
public static void main(String[] args) {
ReverseWordsInString reverser = new ReverseWordsInString();
assert reverser.reverseWords("the sky is blue").equals("blue is sky the") : "Test case 1 failed";
assert reverser.reverseWords(" hello world ").equals("world hello") : "Test case 2 failed";
assert reverser.reverseWords("a good example").equals("example good a") : "Test case 3 failed";
System.out.println("All tests passed!");
}
}