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​