Title Description
Enter a sequence of two integers, and the first sequence represents the stacking order of the stack, judging if the second sequence might be the pop-up order for the stack. Assume that all the numbers that are pressed into the stack are not equal. For example, the sequence 1,2,3,4,5 is the indentation order of a stack, and the sequence 4,5,3,2,1 is a pop-up sequence corresponding to the stack sequence, but 4,3,5,1,2 is not likely to be the pop-up sequence of the stack sequence. (Note: The lengths of the two sequences are equal)
Title Address
https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106?tpId=13&tqId=11174&tPage=2&rp=2 &ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
Ideas
Borrowing an auxiliary stack, traversing the stack sequence, first put in the stack, here is 1, and then determine whether the top element of the stack is the first element of the stack order, here is 4, very obviously 1! =4, so we continue to press the stack, until the equivalent after the start of the stack, out of the stack of an element, then the stack in the order to move backward one bit, until not equal, so that the loop, such as the stack sequence traversal completed, if the secondary stack is not empty, the pop-up sequence is not the stack's popup order.
#-*-coding:utf-8-*-classSolution:defIspoporder (self, PUSHV, POPV):#Write code herestack = [] forXinchpushV:stack.append (x) whileStack andSTACK[-1] = =popv[0]: Stack.pop () popv.pop (0)returnFalseifStackElseTrueif __name__=='__main__': #into the stack: 1,2,3,4,5 #possible out-of-stack: 4,5,3,2,1 #Unable to stack: 4,3,5,1,2result = solution (). Ispoporder ([1,2,3,4,5],[4,3,5,1,2]) Print(Result)
The sword refers to offer 21. Stack push-in, pop-up sequence (stack)