Leetcode 856. Score of Parentheses
Given a balanced parentheses string S
, compute the score of the string based on the following rules:
S
is guaranteed to be a balanced parentheses string, so this is not a concern.(
and )
?
(
and )
and it is guaranteed to be balanced.We can solve the problem using a stack to keep track of the scores. The idea is to maintain a stack where we push the current score of the parentheses at each depth level.
S
.(
, push a 0 onto the stack indicating a new score level.)
, pop from the stack:
import java.util.Stack;
public class ScoreOfParentheses {
public int scoreOfParentheses(String S) {
Stack<Integer> stack = new Stack<>();
stack.push(0); // The score of the current frame
for (char ch : S.toCharArray()) {
if (ch == '(') {
stack.push(0); // Start a new frame
} else {
int v = stack.pop(); // Score of the inner frame
int top = stack.pop();
stack.push(top + Math.max(2 * v, 1));
}
}
return stack.pop();
}
public static void main(String[] args) {
ScoreOfParentheses solution = new ScoreOfParentheses();
System.out.println(solution.scoreOfParentheses("()")); // Output: 1
System.out.println(solution.scoreOfParentheses("(())")); // Output: 2
System.out.println(solution.scoreOfParentheses("()()")); // Output: 2
System.out.println(solution.scoreOfParentheses("(()(()))")); // Output: 6
}
}
The time complexity of this solution is O(n), where n
is the length of the given string S
. This is because we process each character in the string exactly once.
The space complexity is also O(n) due to the usage of the stack, which in the worst case can grow to store all the nested levels of parentheses.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?