Given a balanced parentheses string s
, return the score of the string.
The score of a balanced parentheses string is based on the following rule:
"()"
has score 1
.AB
has score A + B
, where A
and B
are balanced parentheses strings.(A)
has score 2 * A
, where A
is a balanced parentheses string.
Example 1:
Input: s = "()" Output: 1
Example 2:
Input: s = "(())" Output: 2
Example 3:
Input: s = "()()" Output: 2
Constraints:
2 <= s.length <= 50
s
consists of only '('
and ')'
.s
is a balanced parentheses string.The problem asks to calculate the score of a balanced parentheses string based on specific rules. The rules leverage recursion and the structure of nested parentheses. Instead of a recursive approach, a more efficient iterative solution using a stack is possible but not necessary given the problem constraints. This solution utilizes a clever observation to directly calculate the score in linear time.
Core Idea:
The key observation is that the score is determined solely by the innermost ()
pairs and their nesting levels. Each innermost ()
pair contributes a score of 1. The contribution of each ()
pair is then multiplied by 2 for each level of nesting it is within.
Algorithm:
Initialization: We initialize ans
(the total score) to 0 and d
(the depth of nested parentheses) to 0.
Iteration: We iterate through the input string s
.
(
, we increment the depth d
.)
, we decrement the depth d
. Crucially, if the preceding character was an opening parenthesis (
, it indicates an innermost ()
pair at the current depth. The score contribution of this pair is 2d (because d
is decremented immediately afterward). We add this score to ans
.Return: After iterating through the entire string, ans
contains the total score, which is returned.
Time and Space Complexity:
Code Examples:
Python:
class Solution:
def scoreOfParentheses(self, s: str) -> int:
ans = d = 0
for i, c in enumerate(s):
if c == '(':
d += 1
else:
d -= 1
if s[i - 1] == '(':
ans += 1 << d
return ans
Java:
class Solution {
public int scoreOfParentheses(String s) {
int ans = 0, d = 0;
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) == '(') {
d++;
} else {
d--;
if (s.charAt(i - 1) == '(') {
ans += 1 << d;
}
}
}
return ans;
}
}
C++:
class Solution {
public:
int scoreOfParentheses(string s) {
int ans = 0, d = 0;
for (int i = 0; i < s.length(); ++i) {
if (s[i] == '(') {
d++;
} else {
d--;
if (s[i - 1] == '(') {
ans += (1 << d); // More efficient bit shift
}
}
}
return ans;
}
};
Go:
func scoreOfParentheses(s string) int {
ans, d := 0, 0
for i, c := range s {
if c == '(' {
d++
} else {
d--
if s[i-1] == '(' {
ans += 1 << d
}
}
}
return ans
}
All the code examples follow the same algorithm, demonstrating its simplicity and efficiency. The use of bit shifting (1 << d
) is a concise way to calculate 2d.