Sword finger offer | interview question 24: Press in and pop-up sequence of stack

Posted by mark110384 on Thu, 30 Dec 2021 01:23:48 +0100

Knock algorithm series articles

  1. Ten classic sorting algorithms for dry goods and hand tearing
  2. Sword finger offer | understanding interview
  3. Sword finger offer | interview question 2: realizing Singleton mode
  4. Sword finger offer | interview question 3: finding two-dimensional array
  5. Sword finger offer | interview question 4: replace spaces
  6. Sword finger offer | interview question 5: print linked list from end to end
  7. Jianzhi offer | interview question 6: Rebuilding binary tree
  8. Sword finger offer | interview question 7: realizing queue with two stacks
  9. Sword finger offer | interview question 8: minimum number of rotation array
  10. Sword finger offer | interview question 9: Fibonacci number
  11. Sword finger offer | interview question 10: frog jumping steps
  12. Sword finger offer | interview question 11: matrix coverage
  13. Sword finger offer | interview question 12: the number of 1 in binary
  14. Sword finger offer | interview question 13: integer power of value
  15. Sword finger offer | interview question 14: print from 1 to the maximum n digits
  16. Sword finger offer | interview question 15: delete the node of the linked list
  17. Sword finger offer | interview question 16: put the odd number in the array before the even number
  18. Sword finger offer | interview question 17: the penultimate node in the lin k ed list
  19. Sword finger offer | interview question 18: reverse linked list
  20. Sword finger offer | interview question 19: merge two ordered linked lists
  21. Sword finger offer | interview question 20: judge whether binary tree A contains subtree B
  22. Sword finger offer | interview question 21: mirror image of binary tree
  23. Sword finger offer | interview question 22: print matrix clockwise
  24. Sword finger offer | interview question 23: stack containing min function

"Leetcode : https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof

"GitHub : https://gitee.com/nateshao/leetcode/blob/main/algo-notes/src/main/java/com/nateshao/sword_offer/topic_24_validateStackSequences/Solution.java

Sword finger Offer 24 Stack push in and pop-up sequence

Title Description: enter two integer sequences. The first sequence represents the push in order of the stack. Please judge whether the second sequence is the pop-up order of the stack.

Assume that all the numbers pushed into the stack are not equal. For example, sequence {1,2,3,4,5} is the stack pressing sequence of a stack, and sequence {4,5,3,2,1} is a pop-up sequence corresponding to the stack pressing sequence, but {4,3,5,1,2} cannot be the pop-up sequence of the stack pressing sequence.

Example:

Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
 Explanation: we can execute in the following order:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

Example 2:

Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
 Explanation: 1 cannot pop up before 2.
  • Tips:
    1. 0 <= pushed.length == popped.length <= 1000
    2. 0 <= pushed[i], popped[i] < 1000
    3. pushed is the arrangement of popped.

Solution idea: use the stack to press the pop-up elements, and if they are equal, they will be out of the stack.

As shown in the figure below, given a push sequence pushed and a pop sequence popped, the order of push / pop operations (i.e. arrangement) is uniquely determined.

As shown in the figure below, the data operation of the stack has the feature of first in then out, so some pop-up sequences cannot be realized.

Consider borrowing an auxiliary stack to simulate the arrangement of push in 1 pop-up operations. According to whether the simulation is successful, the results can be obtained.

  • Stack operation: execute in the order of stack pressing sequence
  • Stack out operation: after each stack entry, cycle to judge whether "stack top element = current element of pop-up sequence" is true, and pop up all stack top elements that meet the pop-up sequence sequence sequence. "Since the title specifies that all numbers of the stack are not equal, the possibility of the position of each element out of the stack is unique in the cyclic stack (if there are repeated numbers, there are multiple positions that can be out of the stack). Therefore, the stack should be executed immediately when" the top element of the stack = the current element of the pop-up sequence "is encountered.

Algorithm flow:

  1. Initialization: auxiliary stack, pop up the index i of the sequence;
  2. Traverse the stack pressing sequence: each element is marked as num;
    1. Yuan Su num stack;
    2. Loop out of stack: if the stack top element of stack = pop-up sequence element popped[i], perform out of stack and I + +;
    3. Return value: this pop-up sequence is legal if stack is "hurry".

Complexity analysis:

  • Time complexity O(N): where N is the length of the list pushed; Each element can be put on and out of the stack at most once, that is, a total of 2N in and out of the stack operations.
  • Spatial complexity O(N): the auxiliary stack can store up to N elements at the same time.
package com.nateshao.sword_offer.topic_24_validateStackSequences;

import java.util.Stack;

/**
 * @date Created by Shao Tongjie on 2021/11/28 21:53
 * @WeChat official account programmers
 * @Personal website www.nateshao.com cn
 * @Blog https://nateshao.gitee.io
 * @GitHub https://github.com/nateshao
 * @Gitee https://gitee.com/nateshao
 * Description: Stack push in and pop-up sequence
 * Enter two integer sequences. The first sequence represents the push in order of the stack. Please judge whether the second sequence is the pop-up order of the stack.
 * Assume that all the numbers pushed into the stack are not equal. For example, the sequence {1,2,3,4,5} is a stack pressing sequence of a stack,
 * Sequence {4,5,3,2,1} is a pop-up sequence corresponding to the stack pressing sequence, but {4,3,5,1,2} cannot be the pop-up sequence of the stack pressing sequence.
 * https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof
 */
public class Solution {
    public static void main(String[] args) {
        int[] pushed = {1, 2, 3, 4, 5};
        int[] popped = {4, 5, 3, 2, 1};
        int[] popped1 = {4, 3, 5, 1, 2};
        boolean b = validateStackSequences1(pushed, popped);
        System.out.println("b = " + b);// b = true
        boolean b1 = validateStackSequences2(pushed, popped1);
        System.out.println("b1 = " + b1);
    }

    /**
     * Selected answers
     *
     * @param pushed
     * @param popped
     * @return
     */
    public static boolean validateStackSequences1(int[] pushed, int[] popped) {
        if (pushed == null || pushed == null) return false;
        Stack<Integer> stack = new Stack<>();
        int index = 0;
        for (int num : pushed) {
            stack.push(num);
            while (!stack.isEmpty() && stack.peek() == popped[index]) {
                stack.pop();
                index++;
            }
        }
        return stack.isEmpty();
    }

    /**
     * Idea: use the stack to press the pop-up elements, and if they are equal, they will be out of the stack.
     *
     * @param pushed
     * @param popped
     * @return
     */
    public static boolean validateStackSequences2(int[] pushed, int[] popped) {
        if (pushed == null || popped == null) return false;
        Stack<Integer> stack = new Stack<>();// Borrow an auxiliary stack
        int index = 0;
        for (int i = 0; i < pushed.length; i++) {
            stack.push(pushed[i]);// Push 
            //Circular judgment stack is not empty & & stack top element = = current element of pop-up sequence
            while (!stack.isEmpty() && stack.peek().equals(popped[index])) {
                stack.pop();
                index++;
            }
        }
        return stack.isEmpty();
//        return index==popped.length;
    }
}

Reference link: https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof/solution/mian-shi-ti-31-zhan-de-ya-ru-dan-chu-xu-lie-mo-n-2