zoukankan      html  css  js  c++  java
  • python3有效的括号

    #给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
    #有效字符串需满足:
    #左括号必须用相同类型的右括号闭合。
    #左括号必须以正确的顺序闭合。
    strs="'(',')','{','}','[',']'"
    #方法一
    #此处用while比if分别判断要快 while '{}' in strs or '{}' in strs or '[]' in strs: strs=strs.replace('()','') print(strs) strs=strs.replace('{}','') print(strs) strs=strs.replace('[]','') print(strs)
    #方法二
    strdic={'(':')','{':'}','[':']'}
    stack=[]
    for i in strs:
        #循环得到字典的key
        if i in strdic:
            stack.append(i)
        else:
            #列表长度为0
            if len(stack)==0:
                print("false")
            #列表长度不为0
            elif len(stack)!=0:
                a=stack.pop()
                # 弹出stack列表最后一个值,最后一值  i是否在字典里
                if i !=strdic[a]:
                    print("不是对应的括号")
                else:
                    print("是对应括号的值")
    

      

    #方法三 原理与方法二相同,就是速度更快
    strdic={'(':')','{':'}','[':']'}
    stack=[]
    for i in strs:
        if i in strdic:
            if stack:
                mn = stack.pop()
                if strdic[i] == mn:
                    print("TRUE")
                else:
                    print("FALSE")
            else:
                print("stack为空值")
        else:
            stack.append(i)
    

      #链接:https://leetcode-cn.com/problems/valid-parentheses

    上班求生存,下班求发展
  • 相关阅读:
    商业模式--资源整合
    “不小心出卖了领导”
    计算机禁用桌面并且禁用键盘Win+*快捷键组合之后如何打开文件资源管理器
    spring-boot 参数长度、文件上传大小限制问题
    Python 学习基础
    Python字典详解
    Python元组
    Python列表详解
    Python变量类型
    Python字符串详解
  • 原文地址:https://www.cnblogs.com/ljf520hj/p/15230630.html
Copyright © 2011-2022 走看看