856. Score of Parentheses
Problem
Tags: String
, Stack
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 score1
.AB
has scoreA + B
, whereA
andB
are balanced parentheses strings.(A)
has score2 * A
, whereA
is 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 <= 50
s
consists of only'('
and')'
.s
is a balanced parentheses string.
Code
C
// 856. Score of Parentheses (9/24/54176)
// Runtime: 0 ms (93.55%) Memory: 5.50 MB (70.97%)
int scoreOfParentheses (char * s) {
int score = 0, depth = 0;
for (int i = 0; s[i] != '\0'; i++) {
if (s[i] == '(') {
if (s[i + 1] == ')') {
score += 1 << depth;
i++;
} else {
depth++;
}
} else {
depth--;
}
}
return score;
}
GO
// 856. Score of Parentheses (10/4/54176)
// Runtime: 0 ms (82.14%) Memory: 1.90 MB (0.00%)
func scoreOfParentheses(s string) int {
score, depth := 0, 0
for i := 0; i < len(s); i++ {
if s[i] == '(' {
if s[i + 1] != s[i] {
score += 1 << depth
i++
} else {
depth++
}
} else {
depth--
}
}
return score
}
TS
// 856. Score of Parentheses (9/28/54176)
// Runtime: 72 ms (63.64%) Memory: 42.82 MB (54.55%)
function scoreOfParentheses(s: string): number {
let score = 0, depth = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === "(") {
if (s[i + 1] !== s[i]) {
score += 1 << depth;
i++;
} else {
depth++;
}
} else {
depth--;
}
}
return score;
};