JZ21-栈的压入、弹出序列

栈的压入、弹出序列

https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106?tpId=13&tqId=11174&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&tab=answerKey

class Solution {
    public boolean IsPopOrder(int[] pushA, int[] popA) {
        if (pushA.length != popA.length) {
            return false;
        }
        Stack<Integer> stack = new Stack<>();

        int j = 0;
        for (int i = 0; i < pushA.length; i++) {
            if (pushA[i] == popA[j]) { //如果相等
                j++; //一种情况是入栈后直接出栈,这时只需要i++,j++即可 4 和 5

                while (!stack.isEmpty() && stack.peek() == popA[j]) {  //另一种情况是 3(压栈) 4 / 4 3 前面的4等于后面的4,要看3是不是和pop的下一位一致
                    //  2 3(已入栈) 4  -》 4 3 2 如果栈不为空,说明已经有待匹配元素,所有要把2 3 全弹出来看是不是和4后面的一一对应。直到栈为空
                    // 该轮的栈顶元素,要看看之前的元素是否匹配
                    stack.pop();
                    j++;  //popA的已匹配元素++
                }
            } else {
                stack.push(pushA[i]);
            }
        }
        return stack.isEmpty();
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务