题解 | #栈的压入、弹出序列#
栈的压入、弹出序列
https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106
/
import java.util.*; import java.util.ArrayList; public class Solution { public boolean IsPopOrder(int [] pushA, int [] popA) { Stack<Integer> stack = new Stack<>(); int popInd = 0; // 用来记录弹出数组popA 元素移动下标位置 int pushInd = 0; // 用来记录往栈中弹入数组元素的下标 boolean flag = true; // 用来判断是否应该往栈中弹入元素 while (pushInd < pushA.length) { if (flag) { stack.push(pushA[pushInd]); } if (stack.isEmpty()) { // 防止 出现 [1,2,3,4,5],[1,4,2,3,5] 这种情况,导致下一步判断报错 pushInd += 1; flag = true; } else { if (stack.peek() != popA[popInd]) { pushInd += 1; flag = true; } else { stack.pop(); popInd += 1; flag = false; } } } if (stack.isEmpty()) { return true; } else { return false; } } }