Skip to content

Commit 702358d

Browse files
refactor 151
1 parent b1b698c commit 702358d

File tree

1 file changed

+21
-39
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+21
-39
lines changed

src/main/java/com/fishercoder/solutions/_151.java

Lines changed: 21 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -3,46 +3,28 @@
33
import java.util.ArrayDeque;
44
import java.util.Deque;
55

6-
/**
7-
* 151. Reverse Words in a String
8-
9-
Given an input string, reverse the string word by word.
10-
For example,
11-
Given s = "the sky is blue",
12-
return "blue is sky the".
13-
14-
Clarification:
15-
16-
What constitutes a word?
17-
A sequence of non-space characters constitutes a word.
18-
Could the input string contain leading or trailing spaces?
19-
Yes. However, your reversed string should not contain leading or trailing spaces.
20-
How about multiple spaces between two words?
21-
Reduce them to a single space in the reversed string.
22-
*/
23-
246
public class _151 {
25-
public static class Solution1 {
26-
public String reverseWords(String s) {
27-
s.trim();
28-
if (s == null || s.length() == 0) {
29-
return "";
30-
}
31-
String[] words = s.split(" ");
32-
if (words == null || words.length == 0) {
33-
return "";
34-
}
35-
Deque<String> stack = new ArrayDeque<>();
36-
for (String word : words) {
37-
if (!word.equals("")) {
38-
stack.offer(word);
7+
public static class Solution1 {
8+
public String reverseWords(String s) {
9+
s.trim();
10+
if (s == null || s.length() == 0) {
11+
return "";
12+
}
13+
String[] words = s.split(" ");
14+
if (words == null || words.length == 0) {
15+
return "";
16+
}
17+
Deque<String> stack = new ArrayDeque<>();
18+
for (String word : words) {
19+
if (!word.equals("")) {
20+
stack.offer(word);
21+
}
22+
}
23+
StringBuilder stringBuilder = new StringBuilder();
24+
while (!stack.isEmpty()) {
25+
stringBuilder.append(stack.pollLast()).append(" ");
26+
}
27+
return stringBuilder.substring(0, stringBuilder.length() - 1).toString();
3928
}
40-
}
41-
StringBuilder stringBuilder = new StringBuilder();
42-
while (!stack.isEmpty()) {
43-
stringBuilder.append(stack.pollLast()).append(" ");
44-
}
45-
return stringBuilder.substring(0, stringBuilder.length() - 1).toString();
4629
}
47-
}
4830
}

0 commit comments

Comments
 (0)