Title Description:
Given a string that represents a sequence of parentheses, contains the following characters:,,, and ‘(‘, ‘)‘
‘{‘
‘}‘
‘[‘
‘]‘
, determine whether a valid parenthesis sequence.
Have you ever encountered this problem in a real interview? Yes
Sample Example
Parentheses must be "()"
represented in order, "()[]{}"
valid parentheses, but "([)]"
not valid.
labelStack Google
Topic Analysis:
Loop string with left parenthesis in the stack.
In the closing parenthesis, take the element from the top of the stack and pair it to determine the pairing result.
Finally, determine whether the stack is not empty.
Source:
Class solution: # @param {string} s A string # @return {Boolean} whether the string is A valid parentheses def Isvalidparentheses (self, s): # Write Your code here if s none:return False x = [' [', ' (', ' {'] y = ["]" , ")", "}"] z = ["()", "[]", "{}"] res = [] for I in S: if I in x: res.append (i) # into the stack elif i in y:< c13/># If a closing parenthesis is received, but there is no opening parenthesis in res, the direct return is false if res = = []: return false else: temp = Res.pop ( -1) + i # The rest of the situation, out of the stack an opening parenthesis, judging whether the opening parenthesis + the right parenthesis is valid if temp not in Z: return False # If all brace pairs are satisfied, but Res also has an opening parenthesis, return false if Len (res)! = 0: return False return True
Lintcode Python Simple class topic 423. Valid parentheses sequence