Leetcode 946 验证堆栈序列

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

链接:https://leetcode-cn.com/problems/validate-stack-sequences

思路:

1.整一个堆栈,整一个队列

2.把出栈顺序压到队伍里面

3.然后,按元素顺序,一个个push进堆栈里面

4.每push进去一个,判断是不是和队首元素相同,如果同,出队,出栈 直到两者不相同为止。(注意这边)

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
      Queue<Integer> Queue1 = new LinkedList<>();
        Stack<Integer> Stack1=new Stack<>();


        for(int i=0;i<popped.length;i++)
        {
            Queue1.offer(popped[i]);
        }

        //按元素顺序 push 进堆栈
        for(int i=0;i<pushed.length;i++)
        {
//            int push_num=pushed[i];
            Stack1.push(pushed[i]);
            //每push进去一个,都判断是不是和队列首部元素相同,
            //如果相同,出队 出栈 直到两者不相同为止
            while ((!Stack1.isEmpty())&&(Stack1.peek().equals(Queue1.peek())))
            {
                Queue1.poll();
                Stack1.pop();
            }
        }
        if(!Stack1.isEmpty())
        {
            return false;
        }
       return true;

    }
}
原文地址:https://www.cnblogs.com/William-xh/p/13778654.html