856. Score of Parentheses

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int scoreOfParentheses(String s) {
Stack<Integer> stack = new Stack<>();

stack.push(0);
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
stack.push(0);
} else {
int score = stack.pop();
stack.push(stack.pop() + Math.max(score * 2, 1));
}
}

return stack.pop();
}
}

References

856. Score of Parentheses