题目:力扣
给定一个平衡括号字符串 S,按下述规则计算该字符串的分数:
() 得 1 分。
AB 得 A + B 分,其中 A 和 B 是平衡括号字符串。
(A) 得 2 * A 分,其中 A 是平衡括号字符串。
示例 1:
输入: "()"
输出: 1
示例 2:
输入: "(())"
输出: 2
示例 3:
输入: "()()"
输出: 2
示例 4:
输入: "(()(()))"
输出: 6
提示:
S 是平衡括号字符串,且只含有 ( 和 ) 。
2 <= S.length <= 50
官方题解:力扣
没做出来!! 这个计算深度确实很简单 但是我也没想出来 寄。题解里的使用栈的写法我感觉我完全不可能写得出来,有点太秒啦
//作者 https://leetcode.cn/problems/score-of-parentheses/solution/by-lcbin-b9st/
class Solution {
public:
int scoreOfParentheses(string s) {
int ans = 0, d = 0; //d深度 (a+b)*2 == a*2+b*2
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '(') {
++d;
} else {
--d;
if (s[i - 1] == '(') {
ans += 1 << d;
}
}
}
return ans;
}
};