Sword refers to Offer 31. The sequence of pushing and popping the stack (implemented by javascript)

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:

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 be popped before 2.
 

prompt:

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

This question is to test a feature of a stack,

" First-in-last-out " , (that is, the most advanced element can only come out last). When operating the stack, if and only if the operation is performed on one side, that is, a series of operations on the top of the stack that we often say, such as: increase Delete, modify, and check. That's almost it. What we have to do is to simulate how the elements in the stack enter the stack step by step. If you understand this problem, then you can do this problem correctly. Come on! ! ! , The code is as follows: (If you still don’t understand, you can leave a message for questions)

 

/**
 * @param {number[]} pushed
 * @param {number[]} popped
 * @return {boolean}
 */
   var validateStackSequences = function(pushed, popped) {
    //解题的思想:每次与栈的栈顶元素进行比较,相等则删除栈顶元素
    let stack=[];
    let j=0;
    for(let i=0;i<pushed.length;i++){
      stack.push(pushed[i]);//进栈的过程,push()数组的方法
    while(j<pushed.length && stack[stack.length-1]==popped[j]){
            stack.pop();//删除栈顶元素,也就意味着栈的栈顶元素出栈,pop()数组的方法
            j++;//popped移到下一个出栈元素位置
        }
    }   
    //栈的长度为空,说明已经全部出栈,那么也就是合法的出栈序列,返回true
    if(stack.length==0)return true;
    return false; 
};

 

 

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/L_Z_jay/article/details/109275022