forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_151.java
57 lines (49 loc) · 1.69 KB
/
_151.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
49
50
51
52
53
54
55
56
57
package com.fishercoder.solutions;
import com.fishercoder.common.utils.CommonUtils;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* 151. Reverse Words in a String
* Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
*/
public class _151 {
public String reverseWords(String s) {
s.trim();
if (s == null || s.length() == 0) {
return "";
}
String[] words = s.split(" ");
if (words == null || words.length == 0) {
return "";
}
Deque<String> stack = new ArrayDeque<>();
for (String word : words) {
if (!word.equals("")) {
stack.offer(word);
}
}
StringBuilder stringBuilder = new StringBuilder();
while (!stack.isEmpty()) {
stringBuilder.append(stack.pollLast()).append(" ");
}
return stringBuilder.substring(0, stringBuilder.length() - 1).toString();
}
public static void main(String... args) {
/**This main program is to demo:
* a string that contains consecutive empty spaces when splitting by delimiter " ",
* it'll produce a an "" as an element.*/
String s = "a b c";
String[] strs = s.split(" ");
CommonUtils.printArray_generic_type(strs);
}
}