给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
class Solution(object):
def isValid(self, s):
stack = []
judge = {'()','[]','{}'}
for i in s:
if not stack:
stack.append(i)
else:
if stack[-1]+i in judge:
stack.pop()
else:
stack.append(i)
return stack == []
作者:pandawakaka
链接:https://leetcode-cn.com/problems/valid-parentheses/solution/you-xiao-de-gua-hao-python3zhan-by-pandawakaka/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
可以用s中替代的算法……成对的消去最后剩下的就是没法消去的
class Solution:
def isValid(self, s):
while '{}' in s or '()' in s or '[]' in s:
s = s.replace('{}', '')
s = s.replace('[]', '')
s = s.replace('()', '')
return s == ''