Python实现“有效的括号”的两种方法

给定包含'(', ')', '{', '}', '['和']'字符的字符串,判断该字符串是否有效

字符串是否有效:

1、开括号对应同类型的闭括号

2、按开括号顺序匹配闭括号

注意:空字符串有效

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

1:典型的堆栈问题,用字符串模拟处理,代码有注释

def isValid(s):
    """
    :type s: str
    :rtype: bool
    """
    if not s:           #判断字符串是否为空
        return True
    temp_str = ""       #存放临时开括号
    for cha in s:
        if cha == "(" or cha == "[" or cha == "{":       #如果是开括号就放入temp_str字符串中
            temp_str = temp_str + cha
        else:              
            if not temp_str:       #如果temp_str为空,返回False     
                return False
            else:                  
                temp_cha = temp_str[-1]       #取出最新压入的开括号
                temp_str = temp_str[0:-1]     #开括号字符串减一
                if temp_cha == "(" and cha == ")":      #判断开括号和闭括号是否满足要求
                    pass
                elif temp_cha == "[" and cha == "]":
                    pass
                elif temp_cha == "{" and cha == "}":
                    pass
                else:
                    return False
    if not temp_str:     #判断是否存在多余开括号
        return True
    else:
        return False

2:利用列表简化模拟压栈、出栈和判断操作

def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        temp_str = []       #存放临时开括号
        openParentheses = ["(","[","{"]
        combineParentheses = ["()","[]","{}"]
        for cha in s:
            if cha in openParentheses:       #如果是开括号就放入temp_str中
                temp_str.append(cha)
            else:
                if not temp_str:       #如果temp_str为空,返回False
                    return False
                else:
                    temp_cha = temp_str.pop() + cha     #弹出,组合
                    if temp_cha not in combineParentheses:
                        return False
        if not temp_str:     #判断是否存在多余开括号
            return True
        else:
            return False

算法题来自:https://leetcode-cn.com/problems/valid-parentheses/description/

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值