LeetCode 856 括号的分值

原文地址:https://leileiluoluo.com/posts/leetcode-score-of-parentheses.html

1 题目描述
给定一个以括号组成的平衡字符串表达式,基于如下规则计算括号表达式的分值。
1)()的分值为1;
2)AB的分值为A+B,其中A与B均是平衡字符串;
3)(A)的分值为2*A,其中A是平衡字符串。

例子1:
输入:"()"
输出:1

例子2:
输入:"(())"
输出:2

例子3:
输入:"()()"
输出:2

例子4:
输入:"(()(()))"
输出:6

注:
1)字符串仅由'('或')'组成;
2)2 <= len(s) <= 50

题目出处:
https://leetcode.com/problems/score-of-parentheses/

2 解决思路
1)遍历字符数组;
1.1)若当前字符与下个字符是'((',则值为“2*(扩起的字符串值)+扩起字符串后面字符串的值”;
1.2)若当前字符与下个字符是'()',则值为“1+后面字符串的值”。
3)至字符数组最后一个字符结束。

3 golang实现代码
https://github.com/olzhy/leetcode/blob/master/856_Score_Of_Parentheses/test.go

func scoreOfParentheses(s string) int {  
    chars := []rune(s)  
    r := 0  
    for i := 0; i < len(chars)-1; i++ {  
        c, next := chars[i], chars[i+1]  
        if '(' == c && '(' == next {  
            sub := ""  
            depth := 1  
            for i = i + 1; i < len(chars); i++ {  
                if '(' == chars[i] {  
                    depth++  
                } else {  
                    depth--  
                }  
                if 0 == depth {  
                    break  
                }  
                sub += string(chars[i])  
            }  
            if len(chars)-1 == i {  
                return 2 * scoreOfParentheses(sub)  
            }  
            return 2*scoreOfParentheses(sub) + scoreOfParentheses(s[i+1:])  
        } else if '(' == c && ')' == next {  
            sub := ""  
            depth := 1  
            for i = i + 2; i < len(chars); i++ {  
                if '(' == chars[i] {  
                    depth++  
                } else {  
                    depth--  
                }  
                if 0 == depth {  
                    break  
                }  
                sub += string(chars[i])  
            }  
            return 1 + scoreOfParentheses(sub)  
        }  
    }  
    return r  
}  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值