这个题yo,我想着要用字典,可是没想到栈,写半天就是通不过全部测试用例
看了题解才知道,有些人是真的秀,用replace()
不过这题想考的是栈,replace()函数来解是取巧
对我来说就是又get了新知识~
class Solution:
def isValid(self, s: str) -> bool:
if s == "":return True
n = len(s)
if n % 2 != 0:return False
dic = {'(':')','{':'}','[':']'}
stack = []
for i in s:
if i in dic:
stack.append(i)
elif not stack:
return False
elif dic[stack[-1]] == i:
stack.pop()
return len(stack)==0
取巧的replace():
class Solution:
def isValid(self, s: str) -> bool:
if s == "":return True
n = len(s)
if n % 2 != 0:return False
while "()" in s or "[]" in s or "{}" in s:
s = s.replace("()","")
s = s.replace("[]","")
s = s.replace("{}","")
return s == ""
真的佩服