栈的压入、弹出序列

栈的压入、弹出序列

https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106?tpId=13&&tqId=11174&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目思路:
使用一个栈来进行入栈,然后当栈不为空则开始跟popA数组进行比较,若相等则将该元素弹出栈
最后看栈是否为空,如果为空则证明popA是pushA的出栈数组。

 public boolean IsPopOrder(int [] pushA,int [] popA) {
        if(pushA.length == 0 && popA.length == 0)
          return true;
        Stack<Integer> stack = new Stack<>();
        int n = pushA.length;
        for(int pushIndex = 0,popIndex = 0;pushIndex < n; pushIndex++){
            stack.push(pushA[pushIndex]);
            while(popIndex < n && !stack.isEmpty() && stack.peek()==popA[popIndex]){
                stack.pop();
                popIndex++;
            }
        }
        return stack.isEmpty();
    }
剑指offer 文章被收录于专栏

为刷过的每一道题都书写一篇题解,便于重复练习~

全部评论

相关推荐

2025-12-19 16:30
C++
Twilight_m...:这些企业都这B样。本质先把人骗进去,真信有转正猛猛卷,到时候了再来句:“抱歉同学我们业务调整,没hc了,你再看看其他机会吧。”
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

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