题解 | #括号匹配深度#

括号匹配深度

http://www.nowcoder.com/practice/cf1572d8558c4d349fb86c4a529c3cc4

利用栈先入先出的特点

这里不用判断字符串是否合法,减少了许多麻烦 遇到"("就加入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))
全部评论

相关推荐

05-05 21:45
已编辑
广州大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务