image.png
    解法:
    申请一个额外栈,模拟出栈入栈过程,遍历出栈数组,只有辅助栈栈顶元素等于当前出栈数组值时,才会弹出。

    我的代码:

    1. public boolean validateStackSequences(int[] pushed, int[] popped) {
    2. if(pushed==null || popped==null) return false;
    3. if(pushed.length != popped.length) return false;
    4. return process(pushed, popped);
    5. }
    6. public boolean process(int[] pushed, int[] poped){
    7. int index1 =0;
    8. int index2 = 0;
    9. Stack<Integer> stack = new Stack<>();
    10. while(index2 < poped.length && index1 < pushed.length){
    11. if(pushed[index1] != poped[index2]){
    12. stack.add(pushed[index1]);
    13. index1 ++;
    14. }
    15. else if(pushed[index1] == poped[index2]){
    16. index2++;
    17. index1 ++;
    18. while(!stack.isEmpty() &&stack.peek() == poped[index2]){
    19. index2++;
    20. stack.pop();
    21. }
    22. }
    23. }
    24. return stack.isEmpty();
    25. }