Fork me on GitHub

【数据结构】算法 Validate Stack Sequence 验证栈序列

Validate Stack Sequence 验证栈序列

Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.

给了2个序列的入栈,出栈,按照2个栈的顺序,判断是否能将这个栈元素完全处理完。

Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

思路

既然是栈,要出栈肯定是栈顶元素,或者就是下一个要入栈的元素。除了这2个情况,其他肯定不可能。

按照popped数组,扫描pushed数组,一个个入栈

public boolean validateStackSequences(int[] pushed, int[] popped) {
        Stack<Integer> s = new Stack<>();
        int j=0;
        for (int i = 0; i < popped.length; i++) {
            //focus on out stack,
            //if popped stack top not equal pushed e ,push e until find e equal poped top
            //then s.pop,
            while (j<pushed.length&&(!s.isEmpty()||s.peek()!=popped[i])){
                s.push(pushed[j]);
                j+=1;
            }
            if (s.peek()!=popped[i]){
                return false;
            }
            s.pop();
        }
        return true;
    }

Tag

stack

posted @ 2021-04-14 16:12  WilliamCui  阅读(82)  评论(0编辑  收藏  举报