|
3 | 3 | import java.util.ArrayDeque;
|
4 | 4 | import java.util.Deque;
|
5 | 5 |
|
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 |
| - |
24 | 6 | 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(); |
39 | 28 | }
|
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(); |
46 | 29 | }
|
47 |
| - } |
48 | 30 | }
|
0 commit comments