forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseWordsInAString.java
More file actions
33 lines (29 loc) · 874 Bytes
/
ReverseWordsInAString.java
File metadata and controls
33 lines (29 loc) · 874 Bytes
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
public class ReverseWordsInAString {
public static String reverseWords(String s) {
int i, j = 0;
boolean flag = false;
StringBuilder sb = new StringBuilder();
for (i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == ' ') {
if (!flag) {
continue;
} else {
flag = false;
sb.append(s.substring(i + 1, j + 1)).append(" ");
}
} else {
if (!flag) {
flag = true;
j = i;
}
}
}
if (flag) {
sb.append(s.substring(i + 1, j + 1));
}
if (sb.length() > 0 && sb.charAt(sb.length() - 1) == ' ') {
sb.setLength(sb.length() - 1);
}
return sb.toString();
}
}