|
1 | 1 | package com.fishercoder.solutions;
|
2 |
| -/**Given an input string, reverse the string word by word. |
3 | 2 |
|
| 3 | +import com.fishercoder.common.utils.CommonUtils; |
| 4 | + |
| 5 | +import java.util.ArrayDeque; |
| 6 | +import java.util.Deque; |
| 7 | + |
| 8 | +/** |
| 9 | + * 151. Reverse Words in a String |
| 10 | + * Given an input string, reverse the string word by word. |
4 | 11 | For example,
|
5 | 12 | Given s = "the sky is blue",
|
6 |
| -return "blue is sky the".*/ |
| 13 | +return "blue is sky the". |
| 14 | +
|
| 15 | + Clarification: |
| 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 | + */ |
7 | 24 |
|
8 | 25 | public class _151 {
|
| 26 | + |
9 | 27 | public String reverseWords(String s) {
|
10 |
| - if(!s.contains(" ")) return s;//for cases like this: "a" |
11 |
| - if(s.matches(" *")) return "";//for cases like this: " " |
| 28 | + s.trim(); |
| 29 | + if (s == null || s.length() == 0) return ""; |
12 | 30 | String[] words = s.split(" ");
|
13 |
| - StringBuilder stringBuilder = new StringBuilder(); |
14 |
| - for(int i = words.length-1; i >= 0; i--){ |
15 |
| - if(!words[i].equals("") && !words[i].equals(" ")){ |
16 |
| - stringBuilder.append(words[i]); |
17 |
| - stringBuilder.append(" "); |
| 31 | + if (words == null || words.length == 0) return ""; |
| 32 | + Deque<String> stack = new ArrayDeque<>(); |
| 33 | + for (String word : words) { |
| 34 | + if (!word.equals("")) { |
| 35 | + stack.offer(word); |
18 | 36 | }
|
19 | 37 | }
|
20 |
| - stringBuilder.deleteCharAt(stringBuilder.length()-1); |
21 |
| - return stringBuilder.toString(); |
| 38 | + StringBuilder stringBuilder = new StringBuilder(); |
| 39 | + while (!stack.isEmpty()) { |
| 40 | + stringBuilder.append(stack.pollLast()).append(" "); |
| 41 | + } |
| 42 | + return stringBuilder.substring(0, stringBuilder.length()-1).toString(); |
| 43 | + } |
| 44 | + |
| 45 | + public static void main(String... args) { |
| 46 | + /**This main program is to demo: |
| 47 | + * a string that contains consecutive empty spaces when splitting by delimiter " ", |
| 48 | + * it'll produce a an "" as an element.*/ |
| 49 | + String s = "a b c"; |
| 50 | + String[] strs = s.split(" "); |
| 51 | + CommonUtils.printArray_generic_type(strs); |
22 | 52 | }
|
23 | 53 | }
|
0 commit comments