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