Sword refers to the push and pop sequence of offer31-stack

Problem Description

Enter two integer sequences. The first sequence indicates the order in which the stack is pushed. Please judge whether the second sequence is the pop-up order of the stack. Assume that all numbers pushed onto the stack are not equal. For example, the sequence {1,2,3,4,5} is the push sequence of a certain stack, the sequence {4,5,3,2,1} is a pop sequence corresponding to the push sequence, but {4,3 ,5,1,2} cannot be the pop sequence of the stack sequence.
Example 1:

输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
输出:true
解释:我们可以按以下顺序执行:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

Example 2:

输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
输出:false
解释:1 不能在 2 之前弹出。

prompt:

0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed 是 popped 的排列。

Problem-solving ideas (simulation stack):

The auxiliary stack stack for this question simulates the arrangement of push/pop operations. According to whether the simulation is successful, the result can be obtained.
Push operation: Execute in the order of push sequence.
Pop operation: after each stack, loop to determine "top element

Whether the current element of the pop-up sequence is true or not, all the top elements on the stack that conform to the pop-up sequence order will be popped out.
Since all the numbers on the stack are not equal according to the title, the possibility of the position of each element being popped out of the stack in the loop push is The only one (if there are repeated numbers, there are multiple locations that can be popped). Therefore, when encountering "the top element of the stack == the current element of the popped sequence", the popping should be performed immediately

The overall idea of ​​the algorithm:
1. First, construct an auxiliary stack
2. Traverse the pushed array, and push the elements in the pushed array into the stack one by one in each round
3. Compare the elements in the popped array, if the order is the same, push the elements in the array Pop
4. Finally, judge whether there are any remaining elements in the stack

class Solution {
    
    
    public boolean validateStackSequences(int[] pushed, int[] popped) {
    
    
        int len=pushed.length;
        //构造一个模拟栈
        Stack<Integer> stack =new Stack<Integer>();
        int j=0;
        //遍历pushed数组,每趟循环将pushed数组中的元素一一入栈
        for(int i=0;i<len;i++){
    
    
            stack.push(pushed[i]);
            //如果栈顶元素等于弹出序列的当前元素,将符合弹出序列的栈顶元素一一弹出。
            while(!stack.empty() && stack.peek()==popped[j]){
    
    
                stack.pop();
                j++;
            }
        }
        //如果栈中还有剩余元素,则弹出序列不满足要求,返回false
        if(!stack.empty()){
    
    
            return false;
        }
        return true;

    }
}

Guess you like

Origin blog.csdn.net/qq_39736597/article/details/113998960