python【最大括号深度】现有一字符串仅由( , ) , { , } , [ , ]六种括号组成

题目

【最大括号深度】现有一字符串仅由( , ) , { , } , [ , ]六种括号组成。若字符串满足以下条件之一,则为无效字符串:
1、任一类型的左右括号数量不相等;
2、存在未按正确顺序(先左后右)闭合的括号。

输出括号的最大嵌套深度,若字符串无效则输出0.
0<=字符串长度<=100000

输入描述:
一个只包( , ) , { , } , [ , ]的字符串。

输出描述:
一个整数,最大括号深度

示例1:
输入:[]
输出:1

代码实现

#coding=UTF-8
def isValid(s):
        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

def calculate_maxDepth(string,left,right):
		depth = 0
		maxdepth = 0
		for c in string:
			if c == left:
				depth += 1
				maxdepth = max(depth,maxdepth)
			elif c == right:
				depth -= 1
		return maxdepth

string = raw_input("Please input: ")
if isValid(string) == True:
	print max(calculate_maxDepth(string,'(',')'),calculate_maxDepth(string,'[',']'),calculate_maxDepth(string,'{','}'))
else:
	print 0

结果测试

参考链接:

      https://dataartist.blog.csdn.net/article/details/109477554?utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control&dist_request_id=&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-1.control

     Python实现“有效的括号”的两种方法_求兵的博客-CSDN博客_python有效的括号

  • 1
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wellnw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值