题解 | #翻转单词序列#
翻转单词序列
http://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3
看到字符串反转,首先想到栈,因为栈元素先进后出的特点,非常适合实现字符串反转。
public class Solution {
public String ReverseSentence(String str) {
if ("".equals(str)){
return "";
}
String[] strings = str.split(" ");
Stack<String> stack = new Stack<>();
for (String s : strings){
stack.push(s);
stack.push(" ");
}
//去掉多加的一个空格
stack.pop();
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()){
sb.append(stack.pop());
}
return sb.toString();
}
}