问题:
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
解决:
① 使用额外的辅助栈,将遇到出栈的数字之前的数字压入到辅助栈中,一直判断出栈数字是否与辅助栈栈顶元素相等,若不相等,则不能构成正确的出栈序列。
import java.util.ArrayList;
import java.util.Stack;public class Solution {
public static void main(String[] args){ int[] pushA = {1,2,3,4,5}; int[] popA = {4,5,3}; boolean res = IsPopOrder(pushA,popA); System.out.print(res); } public static boolean IsPopOrder(int [] pushA,int [] popA) { if (pushA == null || popA == null || popA.length == 0 || pushA.length == 0 || popA.length != pushA.length){//输入验证 return false; } Stack<Integer> stack = new Stack<>(); int nextPush = 0; int nextPop = 0; while(nextPop < popA.length){ while(nextPush < pushA.length && (stack.isEmpty() || stack.peek() != popA[nextPop])){ stack.push(pushA[nextPush]); nextPush ++; } if (stack.peek() == popA[nextPop]){ stack.pop(); nextPop ++; }else { return false; } } return stack.isEmpty();//return true; } }