856. Score of Parentheses

406 篇文章 0 订阅
406 篇文章 0 订阅

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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值