糖逗 发表于 2020-12-13 14:44:27

C++刷LeetCode(856. 括号的分数)【数学】

题目描述:
给定一个平衡括号字符串 S,按下述规则计算该字符串的分数:

() 得 1 分。
AB 得 A + B 分,其中 A 和 B 是平衡括号字符串。
(A) 得 2 * A 分,其中 A 是平衡括号字符串。
 

示例 1:

输入: "()"
输出: 1
示例 2:

输入: "(())"
输出: 2
示例 3:

输入: "()()"
输出: 2
示例 4:

输入: "(()(()))"
输出: 6
 

提示:

S 是平衡括号字符串,且只含有 ( 和 ) 。
2 <= S.length <= 50

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/score-of-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


class Solution {
public:
    int scoreOfParentheses(string S) {
      int res = 0, cur_num = 0;
      for (int i = 0; i < S.size(); ++i) {
            if (S == '(') {
                cur_num++;
            }else{
                cur_num--;
                if (S == '(')res += pow(2, cur_num);//注意此处的判断!!!
            }
      }
      return res;
    }
};

参考链接:https://leetcode-cn.com/problems/score-of-parentheses/solution/gua-hao-de-fen-shu-by-leetcode/
页: [1]
查看完整版本: C++刷LeetCode(856. 括号的分数)【数学】