class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ res = [] for i in range(len(s)): if s[i] in "([{": res.append(s[i]) else: if len(res) == 0: return False k = res.pop() if (s[i] == ")" and k == '(') or \ (s[i] == ']' and k == '[') or \ (s[i] == '}' and k == '{'): pass else: return False if len(res) == 0: return True else: return False
Solution 2
1 2 3 4 5 6 7 8 9 10 11
class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ while '{}' in s or '()' in s or '[]' in s: s = s.replace('{}', '') s = s.replace('[]', '') s = s.replace('()', '') return s == ''