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

python 有效的括号的实现代码示例,第1张

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/3250663.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-10-04
下一篇 2022-10-04

发表评论

登录后才能评论

评论列表(0条)

保存