题目
思路
- 遍历每个单词,使用栈保存,然后再保存到数组,一个单词作为单位来操作
代码
public String reverseWords(String s) {String str = s.trim();int len = str.length(), j = 0;char[] res = new char[len];Stack<Integer> st = new Stack<>();for (int i = len - 1; i >= 0; i--) {char ch = str.charAt(i);if (ch == ' ' && !st.isEmpty()) {while (!st.isEmpty()) {res[j++] = str.charAt(st.pop());}res[j++] = ' ';};if (ch != ' ') st.push(i);}while (!st.isEmpty()) {res[j++] = str.charAt(st.pop());}StringBuilder ans = new StringBuilder();for (int i = 0; i < j; i++) {ans.append(res[i]);}return ans.toString();}
