856. 括号的分数
- 括号的分数
给定一个平衡括号字符串 S,按下述规则计算该字符串的分数:
() 得 1 分。
AB 得 A + B 分,其中 A 和 B 是平衡括号字符串。
(A) 得 2 * A 分,其中 A 是平衡括号字符串。
示例 1:
输入: “()”
输出: 1
示例 2:
输入: “(())”
输出: 2
示例 3:
输入: “()()”
输出: 2
示例 4:
输入: “(()(()))”
输出: 6
栈,如果碰到)就消去,再讲(前的数字相加或者相乘或者等于1
最后遍历栈,求和就可
class Solution {
public:
int scoreOfParentheses(string S) {
stack<int>sta;
for(int i=0;i<S.length();i++){
if(S[i]=='(') sta.push(0);
else{
if(sta.top()==0){
sta.pop();
sta.push(1);
}
else{
int sum=0;
while(sta.top()!=0){
sum+=sta.top();
sta.pop();
}
sta.pop();
sta.push(2*sum);
}
}
}
int score=0;
while(!sta.empty()){
score+=sta.top();
sta.pop();
}
return score;
}
};
本文介绍了一种计算平衡括号字符串分数的算法。通过使用栈结构,算法能有效处理括号的嵌套,并计算出相应的分数。示例包括对简单和复杂括号字符串的解析。
226

被折叠的 条评论
为什么被折叠?



