LeetCode每日一题- day15

LeetCode每日一题- day15

新手入坑LeetCode,每天打卡一道题
算法不一定很好,只是我自己的一个水平体现,做个自己刷题的记录,欢迎交流学习
(尽量AC LeetCode官方的每日一题)
欢迎交流学习!

题目:856. 括号的分数

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

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

思路:

直接见代码吧

代码:

class Solution {
public:
    int scoreOfParentheses(string s) {
        int n = s.size();
        int ans = 0, count = 0;
        //ans 为最终答案, count记录()的" 层数"
        //每一层就要 * 2
        for(int i = 0; i < n; i ++){
            if(s[i] == '(') count ++;
            else count --;
            if(i > 0){
                if(s[i] == ')' && s[i - 1] == '(') ans += 1 << count; //ans = ans + 2 * count ;
            }
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/Nmj_World/article/details/127235059