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

yipeiwu_com6年前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 实现读取一个excel多个sheet表并合并的方法

如下所示: import xlrd import pandas as pd from pandas import DataFrame DATA_DIR = 'E:/'...

Python 类方法和实例方法(@classmethod),静态方法(@staticmethod)原理与用法分析

Python 类方法和实例方法(@classmethod),静态方法(@staticmethod)原理与用法分析

本文实例讲述了Python 类方法和实例方法(@classmethod),静态方法(@staticmethod)。分享给大家供大家参考,具体如下: demo.py(类方法,@classm...

Python转换时间的图文方法

Python转换时间的图文方法

time模块常用的中时间的转换。 python中的时间戳:通俗讲就是某个时刻的时间,单位是秒; 获取当前时间的时间戳: time.time() 1)没有参数, 2)返回从1970年1月1...

python 运算符 供重载参考

二元运算符 特殊方法 + __add__,__radd__ - __sub__,__rsub__ * __mul__,__rmul__ / __div__...

Python-OpenCV基本操作方法详解

Python-OpenCV基本操作方法详解

基本属性 cv2.imread(文件名,属性) 读入图像 属性:指定图像用哪种方式读取文件 cv2.IMREAD_COLOR:读入彩色图像,默认参数,Opencv 读取彩色图像为BGR...