""" 输入字符串,判断只有括号,且括号配对,求出最深的括号深度 """ def s_true(s): sl = len(s) if sl < 1:#字符长度不能小于1 return False elif sl%2!=0:#字符长度要成双 return False c = 0 while c < sl/2: #把成对的括号去掉,最后判断是否留下字符,如果留下就返回False s = s.replace("{}","").replace("[]","").replace("()","") c=c+1 if len(s)>0: return False else: return True def max_s(s):#换成一种括号,再算最深括号 s = s.replace("(", "{").replace("[", "{").replace(")", "}").replace("]", "}") maxs=0 max_deth =0 for c in s: if c == '{': max_deth+=1 maxs = max(maxs,max_deth) elif c == '}': max_deth-=1 return maxs def max_deth_s(s):#调用函数,先判断字符是否符合,再求最大深度 s_it_true = s_true(s) if s_it_true: maxs =max_s(s) else: return 0 return maxs if __name__ == "__main__": s = input() max_deth = max_deth_s(s) print(max_deth)
2021-1-2,笔记