题目:
""" 给定一个只包括 '(',')','{','}','[',']的字符串 s ,判断字符串是否有效。 有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 """
方法:栈
后遇到的左括号要先闭合(后进先出),例如 s = "{[]}",先闭合(pop)"[]",再"{}"
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 == 1:
return False
pairs = {
")": "(",
"]": "[",
"}": "{",
}
stack = list()
for ch in s:
if ch in pairs:
if not stack or stack[-1] != pairs[ch]:
return False
stack.pop()#先出
else:
stack.append(ch)#后进
return not stack
s = "{[]}"
S = Solution()
result = S.isValid(s)
print(result)