-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathReverseWords.java
More file actions
37 lines (33 loc) · 1.1 KB
/
ReverseWords.java
File metadata and controls
37 lines (33 loc) · 1.1 KB
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
33
34
35
36
37
package ArrayStrings;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ReverseWords {
static String reverse(String str) {
// Reverse String
}
static String reverseP2(String str) {
str = str.trim(); // remove leading and trailing spaces
// str = "hello how are you";
String wordArr[] = str.split(" ");
// wordArr = {"hello", "how", "are", "you"};
List<String> wordList = Arrays.asList(wordArr);
Collections.reverse(wordList);
// wordArr = {"you", "are", "how", "hello"}
return String.join(" ", wordList);
// "you are how hello"
}
public static void main(String[] args) {
String str = "the sky is blue";
String word = "";
String result = "";
for(int i = str.length()-1; i >= 0; i--) {
char singleChar = str.charAt(i);
word += singleChar;
if(singleChar == ' ') {
result += reverse(word);
}
}
System.out.println(result);
}
}