题目
【最大括号深度】现有一字符串仅由( , ) , { , } , [ , ]六种括号组成。若字符串满足以下条件之一,则为无效字符串:
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
结果测试
参考链接: