思路:
- 使用栈来完成反转
- 由于每个单词的字母不用反转,所以直接反转单词即可
代码实现:
import java.util.*;
public class Solution {
public String ReverseSentence(String str) {
Stack<String> s = new Stack<String>();
String[] str1 = str.split(" ");
//单词加入栈中
for(int i=0; i<str1.length;i++){
s.push(str1[i]);
s.push(" ");
}
StringBuilder res = new StringBuilder();
//去掉最后一个空格
if(!s.isEmpty())
s.pop();
//栈遵循先进后厨,单词顺序是反的
while(!s.isEmpty())
res.append(s.pop());
return res.toString();
}
}