856. 括号的分数

给定一个平衡括号字符串 S,按下述规则计算该字符串的分数:

() 得 1 分。
AB 得 A + B 分,其中 A 和 B 是平衡括号字符串。
(A) 得 2 * A 分,其中 A 是平衡括号字符串。

示例 1:

输入: "()"
输出: 1
示例 2:

输入: "(())"
输出: 2
示例 3:

输入: "()()"
输出: 2
示例 4:

输入: "(()(()))"
输出: 6

思路:如果碰到()中间没数字就自己补1,加完后再放到栈里,如果遍历到‘)’而待出栈的不是‘(’时,那每出栈一个‘(’都要把中间夹的数字乘2,最后会得到各个可分割的(),再求和就好了。

class Solution:
    def scoreOfParentheses(self, S: str) -> int:
        stack = []
        for i in S:
            if i=='(':
                stack.append('(')
            else: 
                if stack[-1]=='(':
                    stack[-1]=1
                else:
                    tmp=stack.pop()
                    count=0
                    while tmp!='(':
                        count+=tmp
                        tmp=stack.pop()
                    stack.append(count*2)
        return sum(stack)

链接:https://leetcode-cn.com/problems/score-of-parentheses/solution/python-zhan-he-yi-ci-zhi-jie-bian-li-de-fang-fa-by/

原文地址:https://www.cnblogs.com/USTC-ZCC/p/12951426.html