[leetcode] 856. Score of Parentheses

括号字符串得分计算
本文介绍了一种计算合法括号字符串得分的方法,基于特定规则,使用递归算法解析括号结构,实现字符串得分的计算。

Description

Given a balanced parentheses string S, compute the score of the string 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.

Example 1:

Input:

"()"

Output:

1

Example 2:

Input:

"(())"

Output:

2

Example 3:

Input:

"()()"

Output:

2

Example 4:

Input:

"(()(()))"

Output:

6

Note:

  1. S is a balanced parentheses string, containing only ( and ).
  2. 2 <= S.length <= 50

分析

题目的意思是:给你一个合法的括号字符串,按照题目给定的规则来计算这个字符串的得分。

  • 这种括号字符串可以用递归实现,写着还是不难,按照上面给的三条规则写就完事了,递归的终止条件是“()”,然后返回1就行了,其他的根据规则写就行了。

代码

class Solution {
public:
    int scoreOfParentheses(string S) {
        return solve(S);
    }
    int solve(string s){
        if(s=="()"){
            return 1;
        }
        int cnt=0;
        for(int i=0;i<s.length()-1;i++){
            if(i>0&&cnt==0){
                return solve(s.substr(0,i))+solve(s.substr(i)); 
            }else if(s[i]=='('){
                cnt++;
            }else if(s[i]==')'){
                cnt--;
            }
        }
        return 2*solve(s.substr(1,s.size()-2));
    }
};

参考文献

856. Score of Parentheses

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值