https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106

辅助栈

image.png

  1. public boolean IsPopOrder(int[] pushA, int[] popA) {
  2. int n = pushA.length;
  3. //辅助栈
  4. Stack<Integer> s = new Stack<>();
  5. //遍历入栈的下标
  6. int i = 0;
  7. //遍历出栈的数组
  8. for (int j = 0; j < n; j++) {
  9. //入栈:栈为空或者栈顶不等于出栈数组
  10. while (i < n && (s.isEmpty() || s.peek() != popA[j])) {
  11. s.push(pushA[i]);
  12. i++;
  13. }
  14. //栈顶等于出栈数组
  15. if (s.peek() == popA[j]) {
  16. s.pop();
  17. } else {
  18. //不匹配序列
  19. return false;
  20. }
  21. }
  22. return true;
  23. }