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

有效字符串需满足:
1、左括号必须用相同类型的右括号闭合。
2、左括号必须以正确的顺序闭合。
3、注意空字符串可被认为是有效字符串。
示例一:
输入:s = "()"
输出:true
示例二:
输入:s = "()[]{}"
输出:true
示例三:
输入:s = '([{}])'
输出:true
示例四:
输入:s = '{(}'
输出:false

方法一:字符串

class Solution:
    def isValid(self, s: str) -> bool:
        if not isinstance(s, str):  # 是否是字符串对象
            return False

        if not s:  # 为空返回True
            return True

        if len(s) % 2 != 0:  # 取余不为0,则代表字符串长度为基数,直接返回False
            return False
        
        while '()' in s or '[]' in s or '{}' in s:
            s = s.replace('()', '').replace('[]', '').replace('{}', '')  # 删除字符串中的'()'、'[]'、'{}'

        return s == ''  # 判断s是否为空

方法二:栈

class Solution:
    def isValid(self, s: str) -> bool:
        if not isinstance(s, str):  # 是否是字符串对象
            return False

        if not s:  # 为空返回True
            return True

        if len(s) % 2 != 0:  # 取余不为0,则代表字符串长度为基数,直接返回False
            return False

        dic = {'(': ')', '[': ']', '{': '}'}

        check = []
        for i in s:
            if i in dic.keys():  # 循环判断字符串列表s中的元素是否为左括号
                check.append(i)  # 元素放入列表
            else:
                if not check:  # 表明不存在左括号,但存在右括号,返回False
                    return False
                elif dic[check[-1]] == i:  # 弹出check列表中最后一个元素,作为dic字典key,检测是否与值对应
                    check.pop()  # 对应即弹出check的最后一个元素
                else:  # 不对应则不是有效字符,跳出循环
                    break

        return check == []
原文地址:https://www.cnblogs.com/ghh520/p/15007624.html