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

Brigitte ·
更新时间:2024-09-20
· 502 次阅读

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

有效字符串需满足:

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

示例 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实现的括号匹配判断功能示例使用Python实现一个栈判断括号是否平衡python多行字符串拼接使用小括号的方法Python实现求解括号匹配问题的方法python导入时小括号大作用Python正则表达式实现截取成对括号的方法python正则表达式中的括号匹配问题



括号 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号