Leetcode 856. Score of Parentheses
Given a balanced parentheses string S
, compute the score of the string based on the following rules:
()
: Provides a score of 1
.AB
: Where A
and B
are balanced parentheses strings, the score is A + B
.(A)
: Where A
is a balanced parentheses string, the score is 2 * A
."()"
, Output: 1
"(())"
, Output: 2
"()()"
, Output: 2
"(()(()))"
, Output: 6
We can solve this problem using a stack to help manage the nested structure of the parentheses.
Here’s the step-by-step strategy:
(
:
)
:
()
which contributes 1
or (A)
which contributes 2 * A
.The algorithm processes each character of the string exactly once. Hence, the time complexity is O(n), where n is the length of the string.
#include <iostream>
#include <stack>
int scoreOfParentheses(const std::string& S) {
std::stack<int> stack;
for (char c : S) {
if (c == '(') {
stack.push(0); // Use 0 as a marker for '('
} else {
int currentScore = 0;
while (stack.top() != 0) {
currentScore += stack.top();
stack.pop();
}
stack.pop(); // remove the 0 marker
// If `currentScore` is 0, it means we just closed `()`, score is `1`
// Otherwise, `(A)` contributes `2 * A`
stack.push(currentScore == 0 ? 1 : 2 * currentScore);
}
}
int totalScore = 0;
while (!stack.empty()) {
totalScore += stack.top();
stack.pop();
}
return totalScore;
}
int main() {
std::string s = "(()(()))";
std::cout << "Score of Parentheses: " << scoreOfParentheses(s) << std::endl;
return 0;
}
This code should correctly compute the score for any balanced parentheses string, following the rules provided.
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?