Description
Score of Parentheses
MediumGiven 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 score1.ABhas scoreA + B, whereAandBare balanced parentheses strings.(A)has score2 * A, whereAis 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 <= 50sconsists of only'('and')'.sis a balanced parentheses string.
Solutions
The map keeps the score per level, although a stack could have been used.
Language: javascript()DONE
CPU Performance100.00%
x
Memory Performance68.60%
x
/**
* @param {string} s
* @return {number}
*/
var scoreOfParentheses = function(s) {
const map = new Map([[0, 0]]);
let depth = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === '(') {
depth++;
map.set(depth, 0);
} else {
depth--;
const added = s[i - 1] === '(' ? 1 : 2 * map.get(depth + 1);
map.set(depth, map.get(depth) + added);
}
}
return map.get(0);
};