[leetcode]856. Score of Parentheses
Analysis
心疼奶茶妹妹~—— [马云爸爸恐成最大赢家 哈哈哈]
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.
类似于括号匹配,但是加了一点运算,用栈实现~
Implement
class Solution {
public:
int scoreOfParentheses(string S) {
stack<string> num;
for(auto s:S){
if(s=='(')
num.push("(");
else{
if(num.top()=="("){
num.pop();
num.push("1");
}
else{
int t = 0;
while(num.top() != "("){
t += stoi(num.top());
num.pop();
}
num.pop();
num.push(to_string(2*t));
}
}
}
int res = 0;
while(!num.empty()){
res += stoi(num.top());
num.pop();
}
return res;
}
};