1,题目要求
Given a balanced parentheses string S, compute the score of the string based on the following rule:
对于给定的括号序列,计算对应的最后的结果。
2,题目思路
对于这道题,是括号匹配问题的一个变形:
一个空的括号匹配代表1;
内部有数字的匹配代表内部的2倍;
连续的两个匹配代表相加的和;
因此,对于这样的问题,一般都是利用栈来实现的。
在具体实现时,根据是否匹配以及此时是否有栈顶元素,来进行相应的数据判断。
3,程序源码
class Solution {
public:
int scoreOfParentheses(string S) {
stack<int> s;
for(auto c : S)
{
if(c == '(')
s.push(-1);
else
{
int curr = 0;
while(s.top()!=-1)
{
curr += s.top();
s.pop();
}
s.pop();
s.push(curr == 0? 1 : 2*curr);
}
}
int res = 0;
while(!s.empty())
{
res += s.top();
s.pop();
}
return res;
}
};