美文网首页
2022-06-09 剑指 Offer 31. 栈的压入、弹出

2022-06-09 剑指 Offer 31. 栈的压入、弹出

作者: 16孙一凡通工 | 来源:发表于2022-06-09 09:49 被阅读0次

模拟法,模拟栈的压入和弹出过程

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        // 模拟
       int j=0;
        Stack<Integer> stack=new Stack<Integer>();

        for(int i=0;i<pushed.length;i++){
            
            stack.push(pushed[i]);
                while(!stack.isEmpty() && stack.peek()==popped[j]){
                  stack.pop();
                  j++;
                }

        }
        while(!stack.isEmpty()){
         int temp=stack.pop();
         if(temp!=popped[j]){
           return false;
         }
         j++;
        }
        return true;


    }
}

相关文章

网友评论

      本文标题:2022-06-09 剑指 Offer 31. 栈的压入、弹出

      本文链接:https://www.haomeiwen.com/subject/lstmmrtx.html