classSolution:defisValid(self,s:str) ->bool: d ={'(':')','[':']','{':'}'} result =''for p in s:if p in d.keys(): result += peliflen(result)and{v:k for k, v in d.items()}[p] == result[-1]:# alternative: [k for k, v in d.items() if v == p][0] == result[-1] result = result[:-1]else:returnFalsereturnnotlen(result)
但是其实有一种更简单的聪明做法 : -),直接在字符串中remove掉pairs就好了。
答案
classSolution:defisValid(self,s:str) ->bool:while'[]'in s or'()'in s or'{}'in s: s = s.replace('[]','').replace('()','').replace('{}','')returnnotlen(s)