leetcode 946. Validate Stack Sequences

Just use a stack to simulate the push and pop process

While stack is empty or peek does not equal to popped current value, push value into stack.

While equal, pop stack and consume popped value.

    class Solution {
        public boolean validateStackSequences(int[] pushed, int[] popped) {
            Stack<Integer> s = new Stack<Integer>();
            int i = 0, j = 0;
            while (j < popped.length) {
                if (s.size() == 0 || s.peek() != popped[j]) {
                    if (i == pushed.length) return false;
                    s.push(pushed[i++]);
                }
                else {
                    s.pop();
                    ++j;
                }
            }
            return true;
        }
    }
posted on 2019-03-19 21:19  王 帅  阅读(140)  评论(0编辑  收藏  举报