给定一个平衡括号字符串 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) {
LinkedList<String> list = new LinkedList<>();
int i = 0;
while(i < S.length()){
switch ("" + S.charAt(i)){
case "(":
list.push("(");
break;
case ")":
String s = list.pop();
if(s == "("){
list.push(Integer.toString(1));
}else{
int res = Integer.parseInt(s);
while(true){
s = list.pop();
if(s == "("){
res = res * 2;
list.push(Integer.toString(res));
break;
}else{
res = Integer.parseInt(s) + res;
}
}
}
break;
default:
break;
}
i++;
}
int result = 0;
while(!list.isEmpty()) {
result += Integer.parseInt(list.pop());
}
return result;
}
}