题目描述

https://leetcode.cn/leetbook/read/illustration-of-algorithm/5wh1hj/
image.png

解题思路

此题就是模拟一下栈的压入和弹出,当栈顶元素等于出栈的数组数字时,此时就需要循环出栈,不相等时,接着入栈,返回的时候,如果栈为空,那么全部匹配,如果栈不为空,那么匹配失败。
image.png

  1. class Solution {
  2. public boolean validateStackSequences(int[] pushed, int[] popped) {
  3. Stack<Integer> stack = new Stack<>();
  4. int popIndex = 0;
  5. for (int value : pushed) {
  6. stack.push(value);
  7. // 循环判断是否需要出栈
  8. while (!stack.isEmpty() && stack.peek() == popped[popIndex]) {
  9. stack.pop();
  10. popIndex++;
  11. }
  12. }
  13. return stack.isEmpty();
  14. }
  15. }