Skip to content

Latest commit

 

History

History
43 lines (30 loc) · 999 Bytes

判断栈的弹出序列.md

File metadata and controls

43 lines (30 loc) · 999 Bytes

题目描述

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

##输入描述

压入序列

##输出描述

判断是否为出栈序列的boolean值

##题目分析

解法一  运行时间:26ms  占用内存:629k

public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
      if(pushA.length==0 || popA.length==0){
          return false;
      }
      Stack<Integer> stack = new Stack<Integer>();
      int j=0;
      for(int i=0;i<pushA.length;i++){
          stack.push(pushA[i]);
          while(j<popA.length && stack.peek()==popA[j]){
              j++;
              stack.pop();
          }
      }
      return stack.isEmpty();
    }
}

①判断数组长度,如果为0,返回false

②栈的特性:每次入栈,只要栈中还有元素,就可以多次出栈。

③如果最后栈为空,则这个序列就是弹出序列,否则不是