Leetcode 886 Solution
This article provides solution to leetcode question 886 (score-of-parentheses)
Access this page by simply typing in "lcs 886" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/score-of-parentheses
Solution
class Solution {
public:
int scoreOfParentheses(string S) {
if (S == "()")
return 1;
int cnt = 0;
int i = 0;
for (; i < S.size(); i++)
{
if (S[i] == '(')
cnt++;
else if (S[i] == ')')
cnt--;
if (cnt == 0)
{
i++;
break;
}
}
if (i == S.size())
return 2 * scoreOfParentheses(S.substr(1, S.size() - 2));
else
return scoreOfParentheses(S.substr(0, i)) + scoreOfParentheses(S.substr(i, S.size() - i));
}
};