剑指offer 21.栈的压入、弹出序列
时间:2020-02-24 16:18:00
收藏:0
阅读:68
21. 栈的压入、弹出序列
题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
思路:
新建一个栈,将数组A压入栈中,当栈顶元素等于数组B时,就将其出栈,当循环结束时,判断栈是否为空,若为空则返回true.
1 import java.util.Stack; 2 public class Solution { 3 // 4 public boolean IsPopOrder(int [] pushA,int [] popA) { 5 if(pushA.length == 0 || popA.length == 0) 6 return false; 7 Stack<Integer> stack = new Stack<>(); 8 int j = 0; 9 for(int i = 0; i < pushA.length; i++){ 10 stack.push(pushA[i]); 11 while(!stack.empty() && stack.peek() == popA[j]){ 12 stack.pop(); 13 j++; 14 } 15 } 16 return stack.empty(); 17 } 18 }
原文:https://www.cnblogs.com/hi3254014978/p/12357349.html
评论(0)