利用栈先入先出的特点

这里不用判断字符串是否合法,减少了许多麻烦 遇到"("就加入res 如果遇")"就弹出,res.pop(),并且将当前深度纳入all_depth

def getDepth(line):
    if not line:
        return 0
    res=line[0]
    n=len(line)
    res=[line[0]]
    #print(res)
    i=0
    all_depth=[]
    while i<n-1:
        depth=0
        i+=1
        if line[i]==")":
            depth=len(res)
            all_depth.append(depth)
            res.pop()
        else:
            res.append(line[i])
    return max(all_depth)

line=input()

print(getDepth(line))