题解 | #翻转单词序列#

翻转单词序列

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;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
敢逐云霄志:你打招呼语怎么能这么长,hr都没看下去的欲望,简明扼要说重点,就读于某某学校某某专业,26届应届毕业生,学信网可查,先后在某某公司实习过(如有),然后做过什么项目,想找一份什么样的工作,可实习几个月以上,期待您的回复。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务