Score of parentheses
XXX. Score of Parentheses
String
Stack
Math
Problem Statement:
Given a balanced parentheses string S
, compute the score of the string based on the following rules:
()
has a score of 1.AB
has a score equal toA + B
, whereA
andB
are balanced parentheses strings.(A)
has a score equal to2 * A
, whereA
is a balanced parentheses string.
Approach:
- Maintain a balance variable
bal
to track the depth of nested parentheses. - Iterate through the string, increasing
bal
for each'('
and decreasing it for each')'
. -
Whenever a
'('
is followed by a')'
(i.e.,S[i-1] == '('
), calculate the score for that pair as1 << bal
.- This works because the score doubles with each level of nesting, which can be represented as a left shift.
- Add the computed score to the result variable
ans
.
Complexity:
Time Complexity: O(n), where n
is the length of the string.
Space Complexity: O(1), as we only use variables to track balance and score.
Java Implementation:
public int scoreOfParentheses(String S) {
int ans = 0, bal = 0;
for (int i = 0; i < S.length(); ++i) {
if (S.charAt(i) == '(') {
bal++; // Increment balance for opening parenthesis
} else {
bal--; // Decrement balance for closing parenthesis
// If a complete "()" is found, add score based on depth
if (S.charAt(i-1) == '(')
ans += 1 << bal; // Score doubles with each level of nesting
}
}
return ans;
}