我是靠谱客的博主 可靠溪流,这篇文章主要介绍( LeetCode 946 )验证栈序列 --栈 (Java),现在分享给大家,希望可以做个参考。

请添加图片描述
按照pushed数组的顺序入栈,按照poped数组的顺序出栈,最后栈中为空就可以返回true,否则返回false。

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

       int index = 0;
	   //一直遍历pushed数组把数据压入栈中,直到遇到stack栈顶的数和poped数组的数一样的数据
	   //如上方是示例1,pushed数组一直入栈直到4的时候,才出栈,因为poped数组也有一个4
       for(int i = 0;i < pushed.length;i++){
		   //数据压入栈中
           stack.push(pushed[i]);
		   //栈不为空且pushed数组和poped数组有相同的数
           while(!stack.isEmpty() && stack.peek() == popped[index]){
			   //将当前的数据弹出
               stack.pop();
			   //poped数组继续往后遍历
               index++;
            }
        }  
        //最后整个栈都为空了返回true,否则返回false
        if(!stack.isEmpty()){
            return false;
        }else{
            return true;
        }
    }
}

最后

以上就是可靠溪流最近收集整理的关于( LeetCode 946 )验证栈序列 --栈 (Java)的全部内容,更多相关内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(109)

评论列表共有 0 条评论

立即
投稿
返回
顶部