剑指offer--栈的压入、弹出序列

来源:互联网 发布:linux查看运行的服务 编辑:程序博客网 时间:2024/06/08 13:03

题目描述

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。


分类:栈

解法1:将入栈顺序数组逐个入栈,每次入栈,都判断是否对应出栈数组,也就是是否出栈
例如第一个入栈元素1,入栈以后,判断是否出栈,也就是对应第一个元素是否是1,而其实是4,所以不出栈
就这样一直到入栈元素4,这是相等,所以出栈
并且要向前检查,出栈直到不相等为止

如果出栈顺序正确,那么最后stack里面必然为空
[java] view plain copy
  1. import java.util.ArrayList;  
  2. import java.util.Stack;  
  3. public class Solution {  
  4.     public boolean IsPopOrder(int [] pushA,int [] popA) {  
  5.         if(pushA.length==0return false;  
  6.         Stack<Integer> stack = new Stack<Integer>();  
  7.         int i = 0;  
  8.         int j = 0;  
  9.         while(i<pushA.length){  
  10.             stack.add(pushA[i++]);//逐个入栈  
  11.             while(!stack.isEmpty()&&stack.peek()==popA[j]){//按照顺序出栈  
  12.                 stack.pop();  
  13.                 j++;  
  14.             }  
  15.         }  
  16.         return stack.isEmpty();  
  17.     }  
  18. }  


解法2:和解法1类似,每次入栈,检查是否应该出栈
[java] view plain copy
  1. import java.util.ArrayList;  
  2.   
  3. public class Solution {  
  4.     public boolean IsPopOrder(ArrayList<Integer> pushA,ArrayList<Integer> popA) {  
  5.         int index = 0;  
  6.         while(index<pushA.size() && index>-1){  
  7.             while(index<pushA.size() && pushA.get(index)!=popA.get(0)){  
  8.                 index++;  
  9.             }  
  10.             if(index>=pushA.size()) return false;  
  11.             if(index>=0 && pushA.get(index)==popA.get(0)){  
  12.                 pushA.remove(index);  
  13.                 popA.remove(0);  
  14.                 index--;  
  15.             }                         
  16.         }  
  17.         if(popA.size()==0return true;  
  18.         return false;  
  19.     }  


原文链接  http://blog.csdn.net/crazy__chen/article/details/44998511