类似于中缀表达式转后缀表达的思想

栈的压入、弹出序列

http://www.nowcoder.com/questionTerminal/d77d11405cc7470d82554cb392585106

感觉这个类似于中缀表达式转后缀表达式的那种类型,最先想到的是用两个栈,代码如下:

//使用两个栈来辅助
            Stack<Integer> stack1=new Stack<>();
            Stack<Integer> stack2=new Stack<>();
            for (int i=popA.length-1;i>=0;--i)
                stack2.push(popA[i]);
            for (int i=0;i<pushA.length;++i){
                if (pushA[i]==stack2.peek()){
                    stack2.pop();
                    while (!(stack1.empty()||stack2.empty())
                            &&stack1.peek()==stack2.peek()){
                        stack1.pop();
                        stack2.pop();
                    }
                }else
                    stack1.push(pushA[i]);
            }
            return stack1.empty()&&stack2.empty();

后面发现,stack2只需要从前往后移动就行了,不需要进行压入操作,故可以直接把popA拿过来当栈使用。优化后如下:

//优化,将popA直接当栈来使用
            Stack<Integer> stack1=new Stack<>();
            int point=0;
            for (int i=0;i<pushA.length;++i){
                if (pushA[i]==popA[point]){
                    ++point;
                    while (!(stack1.empty()||point>=popA.length)
                            &&stack1.peek()==popA[point]){
                        stack1.pop();
                        ++point;
                    }
                }else
                    stack1.push(pushA[i]);
            }
            return stack1.empty();
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务