前置条件
给定一个只包括(),[] ,{}的字符串,判断字符串是否有效
- 只使用栈
def isValid(self, s: str) -> bool:
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 # 如果栈不为空说明还有没匹配的括号
- 栈+字典
def isValid(self, s: str) -> bool:
stack = []
map = {'(':')','[':']','{':'}'}
for c in s:
if c in map.keys():
stack.append(map[c])
elif not stack or stack[-1] != c:
return False
else:
stack.pop(0
return True if not stack else False