946. 验证栈序列

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

示例 1:

输入:pushed=[1,2,3,4,5],popped=[4,5,3,2,1]

输出:true

解释:我们可以按一下顺序执行:push(1),push(2),push(3),push(4),pop()->4,push(5),pop()->5,pop()->3,pop()->2,pop()->1

示例2:

输入:pushed=[1,2,3,4,5],popped=[4,3,5,1,2,]

输出:false

解释:1不能在2之前弹出

提示:

1、0<=pushed.length==poped.length<=1000

2、0<=pushed[i],poped[i]<1000

3、pushed是poped的排列


import java.util.Stack;

public class nfs {

    public boolean validateStackSequences(int[] pushed, int[] popped) {

        int N = pushed.length;

        Stack stack =new Stack();

        int j =0;

        for (int x: pushed) {

            stack.push(x);

            while (!stack.isEmpty() && j < N && stack.peek() == popped[j]) {

                stack.pop();

                j++;

            }

    }

    return j == N;

}

public static void main(String[] args){

        int[] pushed = {1,2,3,4,5};

        int[] popped = {4,3,5,1,2};

        nfs nfv =new nfs();

        System.out.print(nfv.validateStackSequences(pushed,popped));

    }

}

你可能感兴趣的:(946. 验证栈序列)