856. Score of Parentheses
- Score of Parentheses python solution
题目描述
Given a balanced parentheses string S, compute the score of the string based on the following rule:
() has score 1
AB has score A + B, where A and B are balanced parentheses strings.
(A) has score 2 * A, where A is a balanced parentheses string.

解析
关键的区别在于()()需要将个数加1,但是(())需要将个数乘以2。所以当出现连续’)‘的时候需要翻倍
同时需要对应’(‘和’)’,需要引入stack的思想。
class Solution:
def scoreOfParentheses(self, S: str) -> int:
stack,cur=[],0
for i in S:
if i=='(':
stack.append(cur)
cur=0
else:
cur+=stack.pop()+max(cur,1)
return cur
Reference
https://leetcode.com/problems/score-of-parentheses/discuss/141777/C%2B%2BJavaPython-O(1)-Space
本文介绍了一种使用Python解决括号字符串分数计算问题的方法。通过分析()()与(())在计算分数时的不同规则,提出了一种利用栈思想的解决方案。对于连续的')',需要将分数翻倍;对于'('和')',需要进行配对。最终,通过一个Solution类的scoreOfParentheses方法实现了这一算法。
890

被折叠的 条评论
为什么被折叠?



