946. 验证栈序列

给定 pushed 和 popped 两个序列,每个序列中的 值都不重复,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true;否则,返回 false 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-stack-sequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.Stack;

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        int pushIdx = 0, popIdx = 0;
        Stack<Integer> stack = new Stack<>();
        while (popIdx < popped.length) {
            while (pushIdx < pushed.length && (stack.isEmpty() || stack.peek() != popped[popIdx])) {
                stack.push(pushed[pushIdx++]);
            }
            if (stack.peek() != popped[popIdx]) {
                return false;
            }
            stack.pop();
            popIdx++;
        }
        return true;
    }
}
posted @ 2021-12-20 13:16  Tianyiya  阅读(28)  评论(0)    收藏  举报