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}2k−1
例如“( () ( () () ) )”, 即 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;
}
};