示例 1:
输入: "()"
输出: 1
示例 2:
输入: "(())"
输出: 2
示例 3:
输入: "()()"
输出: 2
示例 4:
输入: "(()(()))"
输出: 6
方法1:栈
import java.util.Stack;
public class _856_括号的分数 {
public _856_括号的分数(String s) {
int i = scoreOfParentheses(s);
System.out.println(i);
}
public int scoreOfParentheses(String S) {
Stack<Object> stack = new Stack<>();
for (int i = 0; i < S.length(); i++) {
char c = S.charAt(i);
if (c == '(') {
stack.push('(');
} else {
if (stack.peek() == (Character)'(') {
stack.pop();
stack.push(1);
} else {
int sum = 0;
while (stack.peek() != (Character)'(') {
sum = sum + 2*(int)stack.pop();
}
stack.pop();
stack.push(sum);
}
}
}
int total = 0;
while (!stack.isEmpty()) {
total+=(int)stack.pop();
}
return total;
}
}
方法2:
class Solution {
public int scoreOfParentheses(String S) {
int ans = 0, bal = 0;
for (int i = 0; i < S.length(); ++i) {
if (S.charAt(i) == '(') {
bal++;
} else {
bal--;
if (S.charAt(i-1) == '(')
ans += 1 << bal;
}
}
return ans;
}
}