来源:力扣(LeetCode)
https://leetcode-cn.com/problems/fan-zhuan-dan-ci-shun-xu-lcof/
面试题58 - I. 翻转单词顺序
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. “,则输出"student. a am I”。
思路一:将String分隔成字符串数组,然后后向前用StringBuilder串在一起
public String reverseWords(String s) {
String[] str = s.split(" ");
StringBuilder sb = new StringBuilder();
for(int i = str.length-1; i>=0; i--){
if(!str[i].equals("")){
sb.append(str[i]);
sb.append(" ");
}
}
return sb.toString().trim();
}
思路二:建立一个栈来存每个子字符串,最后再串成一串
class Solution {
public String reverseWords(String s) {
Stack<String> stack = new Stack<String>();
for (int i = 0; i < s.length(); i++) {
// 遍历字符串,遇到不为“ ”的字符串,将其放到栈里面
if (s.charAt(i) != ' ') {
int begin = i;
int end = i;
while (end < s.length() && s.charAt(end) != ' ') {
end++;
}
stack.push(s.substring(i, end));
i = end;
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.pop());
sb.append(" ");
}
return sb.toString().trim();
}
}