forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseWordsInAString.java
48 lines (40 loc) · 1.2 KB
/
ReverseWordsInAString.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class ReverseWordsInAString {
// 耗时10ms
public String reverseWords(String s) {
StringBuilder sb = new StringBuilder();
boolean inWord = false;
char[] cc = s.toCharArray();
for (int i = cc.length - 1, idx = 0; i >= 0; i--) {
if (cc[i] != ' ') {
if (!inWord && sb.length() > 0) {
sb.append(' ');
}
inWord = true;
sb.insert(idx, cc[i]);
} else if (inWord) {
idx = sb.length() + 1;
inWord = false;
}
}
return sb.toString();
}
// 耗时18ms
public String reverseWords2(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0, j = 0; i < s.length(); ) {
if (s.charAt(i) == ' ') {
i++;
j = i;
} else if (j >= s.length() || s.charAt(j) == ' ') {
sb.insert(0, s.substring(i, j) + " ");
i = j;
} else {
j++;
}
}
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
}
return sb.toString();
}
}