Score of Parentheses — Stack Depth Doubling
Advertisement
Problem 281 · Score of Parentheses
Difficulty: Medium · Pattern: Stack / Depth Doubling
Rules: () = 1, AB = A+B, (A) = 2*A.
Solutions
# Python — stack approach
def scoreOfParentheses(s):
stack = [0] # start with base score
for c in s:
if c == '(':
stack.append(0)
else:
v = stack.pop()
stack[-1] += max(2*v, 1) # () -> 1, (A) -> 2*A
return stack[0]
# Depth approach O(1) space
def scoreOfParentheses(s):
ans = depth = 0
for i, c in enumerate(s):
if c == '(': depth += 1
else:
depth -= 1
if s[i-1] == '(': ans += 1 << depth
return ans
// Java
public int scoreOfParentheses(String s) {
Deque<Integer> stack = new ArrayDeque<>();
stack.push(0);
for (char c : s.toCharArray()) {
if (c == '(') stack.push(0);
else { int v = stack.pop(); stack.push(stack.pop() + Math.max(2*v, 1)); }
}
return stack.pop();
}
Complexity
- Stack: O(n) time, O(n) space
- Depth trick: O(n) time, O(1) space
Advertisement