首页 > 其他 > 详细

剑指 Offer 31. 栈的压入、弹出序列

时间:2021-04-01 00:02:54      阅读:24      评论:0      收藏:0      [点我收藏+]

题目:

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {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 之前弹出。

 

提示:

  1. 0 <= pushed.length == popped.length <= 1000
  2. 0 <= pushed[i], popped[i] < 1000
  3. 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 }

技术分享图片

 

剑指 Offer 31. 栈的压入、弹出序列

原文:https://www.cnblogs.com/SEU-ZCY/p/14603876.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!