给定一个字符串,逐个翻转字符串中的每个单词。
我的思路:用栈存储每两个' '之间的字符数组,然后弹栈重新用' '拼接起来即可
代码如下:
public void reverseWords(char[] s){ Stack<List<Character>> stack = new Stack<>(); int i = 0; while (i < s.length){ int j = i; List<Character> list = new ArrayList<>(); while (j < s.length && s[j] != ' '){ list.add(s[j]); j++; } i = j+1; stack.push(list); } int index = 0; while (!stack.isEmpty()){ List<Character> list = stack.pop(); for (int j = 0; j < list.size(); j++) { s[index] = list.get(j); index++; } if (index != s.length){ s[index] = ' '; index++; } } }