数据结构题
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
- ()()[]{} 匹配
- ([{()}]) 匹配
- []( 不匹配
- [(]) 不匹配
思路:只要遇到括号匹配的问题,我们就选择用栈,遇到左括号就进栈,遇到右括号,就判断栈顶元素是否与之匹配,匹配的话就pop出栈,不匹配的话就返回false。
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack= []
for c in s:
if c in {'[','{','('}:
stack.append(c)
elif c==')':
if len(stack)>0 and stack[-1]=='(':
stack.pop()
else:
return False
elif c=='}':
if len(stack)>0 and stack[-1]=='{':
stack.pop()
else:
return False
elif c==']':
if len(stack)>0 and stack[-1]=='[':
stack.pop()
else:
return False
if len(stack)>0:
return False
else:
return True