zoukankan      html  css  js  c++  java
  • 给定一个只包括 ‘(‘,‘)‘,‘{‘,‘}‘,‘[‘,‘]‘ 的字符串,判断字符串是否有效。

    有效字符串需满足:
    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 == []
    
  • 相关阅读:
    gcc帮助资料搜找
    由去掉word文档中的一个GoLand复制后残留的底纹说起
    记录一些有趣网站的链接
    linux cpu调度算法发展过程
    啥叫内核线程-搜集
    了解了下啥叫cfs/bfs
    c++重载运算符两种形式的选择
    概念-乐观锁、悲观锁
    go 移位操作的简单自测-移33或65位
    Shell脚本:(delayexec)Cygwin下调用schtasks创建Windows任务计划,实现延迟或定时执行某一命令
  • 原文地址:https://www.cnblogs.com/ghh520/p/15007624.html
Copyright © 2011-2022 走看看