Score of Parentheses(856)

本文介绍了一种计算平衡括号字符串分数的方法,基于三种规则:()得分为1,AB得分为A+B,(A)得分为2*A。通过递归思想解析复杂括号结构,实现高效计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

C++代码:
class Solution {
public:
    int scoreOfParentheses(string S) {
      return helper(S,0,S.length()-1);
    }
private:
    int helper(string &s,int l,int r) {
      if(r - l == 1) return 1;      //”()“情况
      int count = 0;
      for (int i = l; i < r; i++) {          //注意循环到i=r-1
        if(s[i] == '(') count ++;
        else if(s[i] == ')') count--;
        if(count == 0)
          return helper(s,l,i) + helper(s,i+1,r); //“AB”的情况;
      }
      return 2*helper(s,l+1,r-1); //“(A)”的情况
    }
};
Complexity Analysis:

Time complexity : O(n)~O(n^2). 最好的情况:“()()()”; 最坏的情况:“((()))”
Space complexity : O(n).

思路:
  • 递归的思想
  • 关键:如何判断括号匹配情况,是否是平衡的. 当count等于0时平衡, 当count最终不等于0,即“(A)”的情况,如何处理.
思路2:
  • 只算每个“()”外层括号数k,为2k−12^{k-1}2k1

例如“( () ( () () ) )”, 即 21+22+22=102^{1}+2^{2} +2^{2} =1021+22+22=10

Complexity Analysis:

Time complexity : O(n). 遍历字符串一次
Space complexity : O(1).

C++代码:
class Solution {
public:
  int scoreOfParentheses(string S) {
    int count = 1, ans = 0;
    for (int i = 1; i < S.length(); i++) {
      if(S[i] == '(') count ++;
      if(S[i] == ')'){
        if(S[i-1] == '('){        //当出现“()”时
          ans += 1 << (count-1);
        }
        count --;
      }
    }
    return ans;
  }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值