每日一道Leetcode - 856. 括号的分数 【栈】

在这里插入图片描述

class Solution(object):
    def scoreOfParentheses(self, S):
        """
        :type S: str
        :rtype: int
        """
        stack = []
        for x in S:
            if x == '(':
                stack.append('(')
            else:
                if(stack[-1]=='('):
                    a = stack.pop()
                    stack.append(1)
                else:
                    a = stack.pop()
                    temp = 0
                    while(a!='('):
                        temp+=a
                        a = stack.pop()
                    stack.append(2*temp)
        res = sum(stack)
        return res
        

猜你喜欢

转载自blog.csdn.net/weixin_41041275/article/details/113108532