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