LeetCode 856. 括号的分数

题目链接:https://leetcode.cn/problems/score-of-parentheses/

思路如下:

定义一个记录分数的栈,初始时放入 0 0 0 当做答案。

  • 如果遇到左括号,则 0 0 0 入栈。

  • 如果遇到右括号,则弹出栈顶。如果栈顶元素 t t t 0 0 0,则说明右括号是和上一个左括号相邻的,故此时的栈顶加 1 1 1;否则此时的栈顶加 2 ∗ t 2 * t 2t

题目保证 s 是只含有 () 的平衡括号字符串,由于初始时放入了一个 0 0 0,所以最后栈中一定还剩一个元素,这个元素就是答案。

仅需要遍历一遍字符串 s,故时间复杂度为 O ( n ) O(n) O(n)

需要额外的栈空间,故空间复杂度为 O ( n ) O(n) O(n)

C++ 代码如下:

class Solution {
public:
    int scoreOfParentheses(string s) {
        stack<int> score;

        score.push(0);

        for (auto &x : s) {
            if (x == '(') {
                score.push(0);
            } else {
                int t = score.top();
                score.pop();
                if (t == 0) score.top() += 1;
                else score.top() += 2 * t;
            }
        }
        
        return score.top();
    }
};

你可能感兴趣的:(力扣,leetcode,c++,栈)