[Swipe the question bank] Sword refers to Offer_ programming questions, the sequence of pushing and popping the stack.

Title description

Enter two integer sequences. The first sequence indicates the order in which the stack is pushed. Please judge whether the second sequence may be the pop 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 order 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 It cannot be the pop sequence of the push sequence. (Note: The lengths of these two sequences are equal)

Time limit: 1 second Space limit: 32768K Heat index: 408830

Knowledge points of this question:  stack

 

premise:

         Understand the stack: Understand the stack and stack packaging and applications

 

analysis:

1. Create a new array newStack as the stack.

2. Put the elements in pushV into the new stack one by one.

3. If the top element of the new stack is the same as the first element in popV, then these two elements are popped from the stack.

4. When all popV elements are popped out of the stack, it means that it is the pop sequence of the push sequence.

Problem solving:

function IsPopOrder(pushV, popV)
{
    //创建一个新的数组作为栈
    var newStack = [];
    while(pushV.length != 0){
        //将pushV中的元素一个一个往新栈放入
        newStack.push(pushV.shift());
        //如果新栈的栈顶元素与popV中的第一个元素相同,则这两个元素出栈。
        while(newStack.length != 0 && newStack[newStack.length - 1] == popV[0]){
            popV.shift();
            newStack.pop();
        }
    }
    //最后的popV元素全部出栈就符合
    return popV.length == 0;
}

example:

[1,2,3,4,5],[4,3,5,1,2]

Use case diagram

Guess you like

Origin blog.csdn.net/weixin_42339197/article/details/100539191