856. Score of Parentheses

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分;AB形式(A,B都是平衡字符串)的得分=A的得分+B的得分;"(A)"形式(A为一平衡字符串)的得分=2*A的得分。

思路:递归实现,对于每部分字串,从前向后遍历,统计"("与")"的数目。若为"("则计数器加1,否则计数器减1。从计数器为1到下一次计数器为0区间内的字串是1个平衡字符串,递归求解该平衡字符串,按照题意计算分数即可。

 

class Solution {
public:
    int calc(int a,int b,string S){
        //printf("%d %d\n",a,b);
        if(b-a==1) 
            return 1;
        int left=0,sum=0,last=a;
        for(int i=a+1;i<b;i++){
            if(S[i]=='(')
                left++;
            else
                left--;
            if(left==0) {
                sum+=calc(last+1,i,S);
                last=i;
            }
        }
        return sum*2;
    }
    int scoreOfParentheses(string S) {
        int sum=0,left=0,last=0;
        for(int i=0;i<S.size();i++){
            if(S[i]=='(')
                left++;
            else
                left--;
            if(left==0) {
                sum+=calc(last,i,S);
                last=i+1;
            }
        }
        return sum;
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值