给定一个平衡括号字符串 S,按下述规则计算该字符串的分数:
() 得 1 分。
AB 得 A + B 分,其中 A 和 B 是平衡括号字符串。
(A) 得 2 * A 分,其中 A 是平衡括号字符串。
示例 1:
输入: “()”
输出: 1
示例 2:
输入: “(())”
输出: 2
示例 3:
输入: “()()”
输出: 2
示例 4:
输入: “(()(()))”
输出: 6
提示:
S 是平衡括号字符串,且只含有 ( 和 ) 。
2 <= S.length <= 50
思路一:
对于给定的平衡括号字符串,只要遍历这个字符串,定义int型变量count_left来记录左括号的个数,int型变量为count来记录总的分数,从第一个元素开始,遇到‘(’,count_left就加1,遇到‘)’就看其前面的元素是不是‘(’,如果是,则说明要么就是简单的“()”型,要么就是 “(A)”型,count加上2^(count_left-1),然后count_left减少1,如果不是,直接减少1。直到遍历完整个序列。然后返回count,即为总的分数。
代码如下:
class Solution {
public:
int scoreOfParentheses(string S) {
int count = 0;
int count_left = 0;
for(int i = 0;i<S.size();i++){
if(S[i]=='('){
count_left++;
}
else{
if(S[i-1]=='('){
count+=pow(2,count_left-1);
count_left--;
}
else{
count_left--;
}
}
}
return count;
}
};
思路二:
用栈解决的话,如果遇到左括号,则入栈。如果遇到右括号,判断栈顶是不是右括号,如果是则说明是(),出栈并压数字1;否则说明是(A)型,将内部数字全部加起来再次入栈。最后栈内是各种数字,加起来就可以了。
代码如下:
/*class Solution {
public:
int scoreOfParentheses(string S) {
stack<string> s;
for(char& i : S) {
if(i == '(') {
s.push("(");
} else {
if(!s.empty() && s.top() == "(") {
s.pop();
s.push("1");
} else {
int sum = 0;
while(!s.empty() && s.top() != "(") {
sum += stoi(s.top());
s.pop();
}
if(!s.empty()) {
s.pop();
}
s.push(to_string(sum * 2));
}
}
}
int res = 0;
while(!s.empty()) {
res += stoi(s.top());
s.pop();
}
return res;
}
};*/