-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution151.java
More file actions
44 lines (42 loc) · 1.23 KB
/
Solution151.java
File metadata and controls
44 lines (42 loc) · 1.23 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
38
39
40
41
42
43
44
public class Solution151 {
public static String reverseWords(String s) {
if (s == null) {
return s;
}
if (s.trim().isEmpty() || s.length() == 1) {
return s.trim();
}
String[] words = s.trim().split(" ");
reverse(words, 0, words.length - 1);
StringBuilder sb = new StringBuilder();
for (String word : words) {
if (word.trim().isEmpty()) {
continue;
}
sb.append(word);
sb.append(" ");
}
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
private static void reverse(String[] words, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
while (words[i].trim().isEmpty()) {
i++;
}
while (words[j].trim().isEmpty()) {
j--;
}
if (i < j) {
String temp = words[i];
words[i] = words[j];
words[j] = temp;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = " b a";
System.out.println(reverseWords(s));
}
}