Leetcode stack Valid Parentheses

Source: Internet
Author: User

Leetcode stack Valid Parentheses

Valid Parentheses Total Accepted: 17916 Total Submissions: 63366my Submissions

Given a string containing just the characters'(',')','{','}','['And']', Determine if the input string is valid.

The brackets must close in the correct order,"()"And"()[]{}"Are all valid"(]"And"([)]"Are not.


Question: There are three pairs of brackets '(' and ')', '[' and ']', '{' and '}' to determine whether the given bracket string matches.

Idea: Stack

1. Press the stack in case of left brackets

2. when the right parenthesis is encountered, determine whether the bracket at the top of the stack is a pair with the current bracket. If the stack is empty or does not match, the brackets of the entire string do not match. If yes, the top brackets of the stack are output from the stack.

3. If the final stack element is 0, it indicates a string match; otherwise, it does not match.

Complexity: time O (n), Space O (n)

Class Solution:
# @ Return a boolean
Def isValid (self, s ):
If s = '': return True
Stack = []
Left = '([{'; right = ')]}'
For c in s:
If c = '(' or c = '[' or c = '{':
Stack. append (c); continue
For I in xrange (3 ):
If c = right [I]:
If not stack or stack [-1]! = Left [I]:
Return False
Else:
Stack. pop (); continue
Return not 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.