剑指 Offer 31. 栈的压入、弹出序列
题目:
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。
示例 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 之前弹出。
提示:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed
是popped
的排列。
代码:
1 class Solution { 2 public boolean validateStackSequences(int[] pushed, int[] popped) { 3 //长度不一样 4 if(pushed.length!=popped.length){return false;} 5 //有一个为空 6 if((pushed.length==0&&popped.length!=0)||(pushed.length!=0&&popped.length==0)){return false;} 7 //两个都为0 8 if((pushed.length==0&&popped.length==0)){return true;} 9 //处理正常数组 10 List<Integer> list=new ArrayList<>(); 11 for(int i=0;i<pushed.length;i++){ 12 list.add(pushed[i]); 13 } 14 int i=0; 15 int j=0; 16 while(i<list.size()&&j<popped.length){ 17 //退出条件,j比较完,或者i大于list集合的长度 18 if(j>=popped.length||i>list.size()){break;} 19 else if(list.get(i)==popped[j]){ 20 list.remove(i); 21 j++; 22 if(i>0){i--;} //处理下标i不能小于0 23 24 } 25 else{ 26 i++; 27 } 28 29 } 30 if(j>=popped.length){return true;} 31 else{return false;} 32 33 } 34 }
1 class Solution { 2 public boolean validateStackSequences(int[] pushed, int[] popped) { 3 //长度不一样 4 if(pushed.length!=popped.length){return false;} 5 //有一个为空 6 if((pushed.length==0&&popped.length!=0)||(pushed.length!=0&&popped.length==0)){return false;} 7 //两个都为0 8 if((pushed.length==0&&popped.length==0)){return true;} 9 //处理正常数组 10 11 Stack<Integer> stack =new Stack<>(); 12 int i=0; 13 for(int num : pushed){ 14 stack.push(num); 15 while(!stack.isEmpty()&&stack.peek()==popped[i]){ 16 stack.pop(); 17 ++i; 18 } 19 } 20 21 if(i>=popped.length){return true;} 22 return false; 23 } 24 }
分类:
leetcode
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术