856. 括号的分数
856. 括号的分数
给定一个平衡括号字符串 S,按下述规则计算该字符串的分数:
()得 1 分。AB得A + B分,其中 A 和 B 是平衡括号字符串。(A)得2 * A分,其中 A 是平衡括号字符串。
示例 1:
输入: "()" 输出: 1
示例 2:
输入: "(())" 输出: 2
示例 3:
输入: "()()" 输出: 2
示例 4:
输入: "(()(()))" 输出: 6
提示:
S是平衡括号字符串,且只含有(和)。2 <= S.length <= 50
func scoreOfParentheses(s string) int {
n := len(s)
// 1. ()得一分
if n == 2 {
return 1
}
for i,bal := 0,0;;i++{
if s[i] == '(' {
bal++
} else {
bal--
if bal == 0 {
if i == n-1 {
// 2.(A) 得 2 * A 分,其中 A 是平衡括号字符串。
return 2 * scoreOfParentheses(s[1:n-1])
}
// 3.AB 得 A + B 分,其中 A 和 B 是平衡括号字符串。
return scoreOfParentheses(s[:i+1]) + scoreOfParentheses(s[i+1:])
}
}
}
}
浙公网安备 33010602011771号