题解 | #翻转单词序列#
翻转单词序列
http://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3
//之前做过一道比这个还复杂的题,主要就是使用栈的思路。那道题涉及 “undo” "redo"单词,题意是遇到"undo",将上一个单词删除,遇到"redo"将删除的操作撤销,即 将最近一次删除的单词再添加回来
import java.util.Stack;
public class Solution {
public String ReverseSentence(String str) {
String word = new String();
String result = new String();
Stack<String> stack = new Stack<>();
for(int i = 0; i < str.length(); i++){
char ch = str.charAt(i);
if( ch != 32){
word = word + ch;
}else{
stack.push(word);
word = new String();
}
}
stack.push(word);
while( !stack.isEmpty()){
if(stack.size() != 1)
result = result + stack.peek() + " ";
else
result = result + stack.peek();
stack.pop();
}
return result;
}
}