题目

image.png

思路

  • 遍历每个单词,使用栈保存,然后再保存到数组,一个单词作为单位来操作

    代码

    1. public String reverseWords(String s) {
    2. String str = s.trim();
    3. int len = str.length(), j = 0;
    4. char[] res = new char[len];
    5. Stack<Integer> st = new Stack<>();
    6. for (int i = len - 1; i >= 0; i--) {
    7. char ch = str.charAt(i);
    8. if (ch == ' ' && !st.isEmpty()) {
    9. while (!st.isEmpty()) {
    10. res[j++] = str.charAt(st.pop());
    11. }
    12. res[j++] = ' ';
    13. };
    14. if (ch != ' ') st.push(i);
    15. }
    16. while (!st.isEmpty()) {
    17. res[j++] = str.charAt(st.pop());
    18. }
    19. StringBuilder ans = new StringBuilder();
    20. for (int i = 0; i < j; i++) {
    21. ans.append(res[i]);
    22. }
    23. return ans.toString();
    24. }