Given a balanced parentheses string S
, compute the score of the string based on the following rule:
()
has score 1AB
has scoreA + B
, where A and B are balanced parentheses strings.(A)
has score2 * 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:
S
is a balanced parentheses string, containing only(
and)
.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;
}
};