The sword refers to the offer 31. The sequence of pushing and popping the stack

The sword refers to the offer 31. The sequence of pushing and popping the stack

Title description

Insert picture description here

Problem-solving ideas

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();
    }
}

Guess you like

Origin blog.csdn.net/cys975900334/article/details/115080455