题目抽象:给定一个首尾可能带空格的字符串,请让你翻转该字符串。首尾不能有多余空格。如果全部是空格,请返回原字符串。
- 实现拆分单词的操作。一个单词为:从不是空格的字符开始到是空格的前一个字符结束,即为一个单词。
- 借助栈来存放分离出来的单词
public static String ReverseSentence(String str) { if (str == null || str.length() < 2) { return str; } StringBuilder tem = new StringBuilder(); Deque<String> stack = new LinkedList<>(); String result = ""; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) != ' ') { tem.append(str.charAt(i)); } if (str.charAt(i) == ' ' && tem.length() != 0) { stack.push(tem.toString()); tem.delete(0, tem.length()); } } if (tem.length() != 0) { stack.push(tem.toString()); } if (stack.isEmpty()) { return str; } result = result + stack.pop(); while (!stack.isEmpty()) { result = result + " " + stack.pop(); } return result; }