856. Score of Parentheses
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Solution { int helper(string& s, int& i, int d = 0) { int score = 0; int st = 0; while(i < s.length()) { if(s[i] == '(') { if(st == 0) { st++; } else { score += 2*helper(s,i,d+1); } } else { st--; if(st == 0) { return score ? score : 1; } else { score += 1; } } i++; } return score; } public: int scoreOfParentheses(string S) { int i = 0; int res = 0; while(i < S.length()) { res += helper(S,i); i++; } return res; } };
|