剑指offer_ 栈的压入、弹出序列

题目描述

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

解题思路:

设置一个栈模拟一下入栈出栈操作就行了

 1 import java.util.*;
 2 
 3 public class Solution {
 4     public boolean IsPopOrder(int [] pushA,int [] popA) {
 5       Stack<Integer> stack = new Stack<>();
 6         int pushIndex=0;
 7         int popIndex=0;
 8       for(int i=0;i<pushA.length;i++){
 9           stack.push(pushA[pushIndex++]);
10           while(popIndex<pushA.length&&!stack.isEmpty()&&stack.peek()==popA[popIndex]){
11               stack.pop();
12               popIndex++;
13           }
14       }
15         return stack.isEmpty();
16     }
17 }

 

posted @ 2019-08-31 10:13  chyblogs  阅读(101)  评论(0)    收藏  举报