-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverseWords.java
33 lines (31 loc) · 997 Bytes
/
ReverseWords.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
33
package brian;
/**
* Created by brian on 7/11/17.
*/
public class ReverseWords {
public String reverseWordsByPointers(String s) {
StringBuilder answer = new StringBuilder();
int j = s.length();
for (int i = s.length() - 1; i >= 0; i--) {
// s = " the sky is blue "
// i
// j
if (s.charAt(i) == ' ') {
j = i;
} else if (i == 0 || s.charAt(i - 1) == ' ') {
answer.append(s.substring(i, j) + " ");
}
}
return answer.toString().trim();
}
public String reverseWordsByArray(String s) {
String[] splitedWords = s.split("\\s+");
// splitedWords = ["the", "sky", "is", "blue"]
String answer = "";
for (int i = splitedWords.length - 1; i >= 0; i--) {
answer += splitedWords[i] + " ";
}
// answer = "blue is sky the"
return answer.trim();
}
}