str.replace(old, new[, max]): # old -- 将被替换的子字符串。 # new -- 新字符串,用于替换old子字符串。 # max -- 可选字符串, 替换不超过 max 次
# https://leetcode.cn/problems/valid-parentheses/# 给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。# 有效字符串需满足:# 左括号必须用相同类型的右括号闭合。# 左括号必须以正确的顺序闭合。# 每个右括号都有一个对应的相同类型的左括号。class Solution: def isValid(self, s: str) -> bool: while '{}' in s or '()' in s or '[]' in s: s = s.replace('{}', '') s = s.replace('[]', '') s = s.replace('()', '') return s == ''if __name__ == '__main__': s = "({}{}{})" print(Solution().isValid(s)) # True