使用栈
遍历字符串中的每个字符,如果是左括号'(',将右括号‘)’压入栈,如果是左括号‘[’,将右括号‘]’压入栈,如果是左括号‘{’,将右括号‘}’压入栈,在此有三种情况
1.字符串里括号多余了,也就是字符串的长度不是偶数一定不匹配
2.括号没有多余,但是括号的类型没有匹配
3.字符串里的左括号或者右括号多余了
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 != 0:
return False
stack = []
for c in s:
if c == '(':
stack.append(')')
elif c == '[':
stack.append(']')
elif c == '{':
stack.append('}')
elif not stack or stack[-1] != c:
return False
else:
stack.pop()
return True if not stack else False
使用字典
通过对比上下两个代码,很类似,就是将上面的每次判断为‘(’,'[','{'时,将‘)’,']','}'压入栈中的操作转换为字典映射了
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mapping = {'(': ')', '[':']', '{':'}'}
for c in s:
if c in mapping.keys():
stack.append(mapping[c])
elif not stack or stack[-1] != c:
return False
else:
stack.pop()
return True if not stack else False