剑指offer 31. 栈的压入、弹出序列

剑指offer 31. 栈的压入、弹出序列

题目描述

在这里插入图片描述

解题思路

class Solution {
    
    
    public boolean validateStackSequences(int[] pushed, int[] popped) {
    
    
        if (pushed.length == 0)
            return true;

        Stack<Integer> stk = new Stack<>();
        int indexOfPop = 0;

        for (int num : pushed) {
    
    
            stk.push(num);
            //循环判断,若栈顶元素等于 poped 中的当前元素,则出栈
            while (!stk.isEmpty() && stk.peek() == popped[indexOfPop]) {
    
    
                stk.pop();
                indexOfPop++;
            }
        }
        //仅当栈为空时,才说明是合法的出栈序列
        return stk.isEmpty();
    }
}

猜你喜欢

转载自blog.csdn.net/cys975900334/article/details/115080455