(没有借鉴别人的代码,全是自己整出来的)序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列

核心思路:
用弹出序列去模拟 进战和出战操作
import
java.util.ArrayList; import java.util.Stack; public class Solution { boolean IsPopOrder(int[] pushA, int[] popA) { // 用出站顺序去匹配 Stack<Integer> s1 = new Stack<Integer>(); s1.push(pushA[0]); int i = 1; int j = 0;// 要消除的匹配规则 while (j < popA.length) { // 用popA数组里面的值去消除另外一个数组 // 先进来和匹配规则进行比较 if (!s1.isEmpty() && popA[j] == s1.peek()) { s1.pop(); j++; continue; } // 将 直到 出站元素第一个的依次入栈,然后将A出站 for (; i < pushA.length;) { if (i == pushA.length - 1 && pushA[i] != popA[j]) return false; if(popA[j] ==break; } while (popA[j] != pushA[i] && i<pushA.length){ s1.push(pushA[i]); i++; } } i++; j++; } if(!s1.isEmpty()) return false; return true; } }
原文地址:https://www.cnblogs.com/cs-lcy/p/7485233.html