python 有效的括号的实现代码示例

yipeiwu_com7年前Python基础

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

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true
示例 2:

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

输入: "(]"
输出: false
示例 4:

输入: "([)]"
输出: false
示例 5:

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

注意此处所用代码为python3

class Solution:
  def pipei(self,m:str,c:str) -> bool:
    if m=='(' and c==')':
      return True
    elif m=='[' and c==']':
      return True
    elif m+c == '{}':
      return True
    else :
      return False
  def isValid(self, s: str) -> bool:
    lens = len(s)
    if lens == 0 :
      return True
    if s[0]==')' or s[0]==']' or s[0]=='}' :
      return False
    lis = []
    lis.append(s[0])
    for i in range(1,lens) :
      if len(lis) :
        tmp = lis.pop()
        if self.pipei(tmp,s[i]) :
          pass
        else :
          lis.append(tmp)
          lis.append(s[i])
      else :
        lis.append(s[i])
    if len(lis) :
      return False
    return True

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python常用的json标准库

当请求 headers 中,添加一个name为 Accept,值为 application/json 的 header(也即“我”(浏览器)接收的是 json 格式的数据),这样,向服务...

python 定义类时,实现内部方法的互相调用

每次调用内部的方法时,方法前面加 self. 举例: 例子参考百度知道里面的回答 class MyClass: def __init__(self): pass de...

Python中新式类与经典类的区别详析

1.新式类与经典类 在Python 2及以前的版本中,由任意内置类型派生出的类(只要一个内置类型位于类树的某个位置),都属于“新式类”,都会获得所有“新式类”的特性;反之,即不由任意内置...

用Python抢过年的火车票附源码

用Python抢过年的火车票附源码

前言:大家跟我一起念,Python大法好,跟着本宝宝用Python抢火车票 首先我们需要splinter 安装: pip install splinter -i http://pyp...

mysql 之通过配置文件链接数据库

mysql 之通过配置文件链接数据库 配置文件jdbc.properties ##MySQL driver=com.mysql.jdbc.Driver url=jdbc\:mysql...