Js used to prove safety brush offer (stack push, pop sequence)

Title Description

Two input sequence of integers, the first sequence representing a pressed stack order, determines whether it is possible for the second sequence the order of the pop-up stack. All figures are not pushed onto the stack is assumed equal. Such as a sequence of a sequence of 1,2,3,4,5 is pressed into the stack, the push sequence is 4,5,3,2,1 sequence corresponding to a sequence of pop, but 4,3,5,1,2 it is impossible to push pop-up sequence of the sequence. (Note: the length of the two sequences are equal)

Thinking

Borrow an auxiliary stack, push traversal order, into a first talk about the stack, here 1, is determined and then the top element is not out of the first element stack order, this is 4, it is clear that a ≠ 4 so we continue to push until after the start of an equal stack, the stack is an element, it will move back one, until the order is not equal to the stack, and so the cycle Yazhan order traversal is complete, if the auxiliary stack is not empty described sequence is not the sequence of pop pop stack.

For example:

Drawing 1,2,3,4,5

Stack 4,5,3,2,1

1 into the first auxiliary stack, when the stack 1 ≠ 4, continued stack 2

At this time, the stack 2 ≠ 4, continue to stack 3

At this time, the stack 3 ≠ 4, 4 continue to stack

At this time, the stack 4 = 4, the stack 4, a pop-up sequence back, in this case the auxiliary stack 5 inside 1,2,3 ,,

At this time, the stack 3 ≠ 5, 5 continue to push

5 = At ​​this point the stack 5, the stack 5, a pop-up sequence back, in this case the auxiliary stack 3 which is 2,3 ,,

….

Followed by the implementation, and finally the auxiliary stack is empty. If not empty pop-described sequence is not the sequence of pop stack.

Cattle off network link

js code

function IsPopOrder(pushV, popV)
{
    // write code here
    if (pushV.length === 0) return true
    const stack = []
    for (let i of pushV){
        stack.push(i)
        while (stack[stack.length-1] === popV[0] && stack.length !== 0){
            stack.pop()
            popV.shift()
        }
    }
    return stack.length === 0 ? true : false
}

Guess you like

Origin www.cnblogs.com/dpnlp/p/yongjs-shua-jian-zhioffer-zhan-de-ya-ru-dan-chu-xu.html