[leetcode刷题(easy)]之六: 有效的括号

题目描述:

给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

输入: "()[]{}"
输出: true

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

输入: "{[]}"
输出: true

解题思路:

如果输入括号是有效的,'{}'、'[]'、'()'这三种组合必有其一,将其用空字符串替换,会出现新的'{}'、'[]'、'()'之一,再用空字符串替换,如此循环,直到整个字符串为空(代表输入是有效的),或者字符串不为空,却不再包含'{}'、'[]'、'()'之一(代表输入是无效的)。

提交结果:

执行用时 : 88 ms, 在Valid Parentheses的Python提交中击败了10.78% 的用户

内存消耗 : 11.7 MB, 在Valid Parentheses的Python提交中击败了29.65% 的用户

代码:

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        
        while '{}' in s or '[]' in s or '()' in s:
            s = s.replace('{}', '')
            s = s.replace('[]', '')
            s = s.replace('()', '')

        if not s:
            return True
        else:
            return False

猜你喜欢

转载自blog.csdn.net/weixin_41931548/article/details/89202575