Leetcode 886 Solution

This article provides solution to leetcode question 886 (score-of-parentheses)

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));
    }
};