forked from algorithm009-class01/algorithm009-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseWords.java
More file actions
36 lines (33 loc) · 1.15 KB
/
ReverseWords.java
File metadata and controls
36 lines (33 loc) · 1.15 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
package str;
import java.util.ArrayDeque;
import java.util.Deque;
public class ReverseWords {
public String reverseWords(String s) {
int left = 0, right = s.length() - 1;
//去掉字符串开头的空白字符
while (left <= right && s.charAt(left) == ' ') ++left;
//去掉字符串末尾的空白字符
while (left <= right && s.charAt(right) == ' ') --right;
Deque<String> d = new ArrayDeque<>();
StringBuilder word = new StringBuilder();
while (left <= right) {
char c = s.charAt(left);
if ((word.length() != 0) && (c == ' ')) {
//将单词push到队列的头部
d.offerFirst(word.toString());
word.setLength(0);
} else if (c != ' ') {
word.append(c);
}
++left;
}
d.offerFirst(word.toString());
return String.join(" ", d);
}
public static void main(String[] args) {
String s = "the sky is blue";
ReverseWords reverseWords = new ReverseWords();
String r = reverseWords.reverseWords(s);
System.out.println(r);
}
}