The sword refers to offer 21. Stack push-in, pop-up sequence (stack)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.