给定一个平衡括号字符串 S,按下述规则计算该字符串的分数:
()得 1 分。AB得A + B分,其中 A 和 B 是平衡括号字符串。(A)得2 * A分,其中 A 是平衡括号字符串。
示例 1:
输入: "()"
输出: 1
示例 2:
输入: "(())"
输出: 2
示例 3:
输入: "()()"
输出: 2
示例 4:
输入: "(()(()))"
输出: 6
提示:
S是平衡括号字符串,且只含有(和)。2 <= S.length <= 50
解题答案
class Solution {
public int scoreOfParentheses(String s) {
Stack<Integer> stack = new Stack<>();
stack.push(0);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(0);
} else {
int top = stack.pop();
top = stack.pop() + Math.max(top * 2, 1);
stack.push(top);
}
}
return stack.peek();
}
}