题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)【运行时间:16ms 占用内存:8264k】
import java.util.*; public class Solution { public boolean IsPopOrder(int [] pushA,int [] popA) { if(pushA.length!=popA.length) return false; Stack<Integer> sk=new Stack<Integer>(); //定义索引用来控制popA数组的下标 int index=0; for(int i=0;i<pushA.length;i++){ sk.push(pushA[i]); //如果栈顶元素和popA[index]相等,则sk.pop(),索引后移 while(!sk.isEmpty()&&sk.peek()==popA[index]){ index++; sk.pop(); } } return sk.isEmpty(); } }【运行时间:12ms 占用内存:8404k】
import java.util.ArrayList; public class Solution { public boolean IsPopOrder(int [] pushA,int [] popA) { ArrayList<Integer> list=new ArrayList<Integer>(); if(pushA.length!=popA.length) return false; int index=0; for(int i=0;i<pushA.length;i++){ list.add(pushA[i]); while(list.size()!=0&&list.get(list.size()-1)==popA[index]){ list.remove(list.size()-1); index++; } } return list.size()==0; } }