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

栈的压入、弹出序列

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

相关推荐

能干的三文鱼刷了10...:公司可能有弄嵌入式需要会画pcb的需求,而且pcb能快速直观看出一个人某方面的实力。看看是否有面试资格。问你问题也能ai出来,pcb这东西能作假概率不高
点赞 评论 收藏
分享
ZywOo_求职版:谁问你了....
投递字节跳动等公司8个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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