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 2022-06-16 15:41  MaXianZhe  阅读(19)  评论(0编辑  收藏  举报

导航