JZ31 栈的压入、弹出序列

描述

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
1. 0<=pushV.length == popV.length <=1000
2. -1000<=pushV[i]<=1000
3. pushV 的所有数字均不相同
 

示例1

输入:
[1,2,3,4,5],[4,5,3,2,1]
返回值:
true
说明:
可以通过push(1)=>push(2)=>push(3)=>push(4)=>pop()=>push(5)=>pop()=>pop()=>pop()=>pop()
这样的顺序得到[4,5,3,2,1]这个序列,返回true    

复制代码
public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        Stack<Integer> stack = new Stack<>();
        int indexA = 0;
        int indexB = 0;
        
        while (indexA < pushA.length && indexB < pushA.length) {
            
            if (!stack.empty() && stack.peek() == popA[indexB]) {
                stack.pop();
                indexB++;
                continue;
            }
            
            if (pushA[indexA] != popA[indexB]) {
                stack.push(pushA[indexA]);
                indexA++;
                continue;
                
            }
            if (pushA[indexA] == popA[indexB]) {
                indexA++;
                indexB++;
                continue;
            }
            
            
        }
        
        while (indexB < pushA.length && !stack.empty()) {
            if (popA[indexB] == stack.pop()) {
                indexB++;
            } else {
                return false;
            }
        }
        
        if (stack.empty()) {
            return true;
        }
        
        return false;
    }
}
复制代码

 

posted on   MaXianZhe  阅读(21)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示