题解 | #括号序列#
括号序列
http://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
两种题型:
只有一种括号匹配可以用count
def matchParentheses(self, string): count = 0 for i in range(len(string)): if string[i] == '(': count += 1 else: count -= 1 if count < 0: return False return True if count == 0 else False
有多种括号匹配时 用count做没法完成“({)}”这样的edge case,所以要用stack来match
class Solution: def isValid(self , s ): # write code here stack = [] for i in range(len(s)): if s[i] == '(': stack.append(')') elif s[i] =='[': stack.append(']') elif s[i] =='{': stack.append('}') elif stack == []: return False elif s[i] != stack[-1]: return False else: stack.pop() return True if stack == [] else False