leetcode 856. Score of Parentheses

Posted いいえ敗者

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 856. Score of Parentheses相关的知识,希望对你有一定的参考价值。

Given a balanced parentheses string S, compute the score of the string based on the following rule:

() has score 1
AB has score A + B, where A and B are balanced parentheses strings.
(A) has score 2 * A, where A is a balanced parentheses string.
Example 1:

Input: "()"
Output: 1
Example 2:

Input: "(())"
Output: 2
Example 3:

Input: "()()"
Output: 2
Example 4:

Input: "(()(()))"
Output: 6
Note:

S is a balanced parentheses string, containing only ( and ).
2 <= S.length <= 50

对于当前字符,如果是‘(‘记录他的位置,如果是‘)‘
有两种状态,要么是() 要么是(()) 所以用个数组去维护与)对应的(之间的数的和。具体见代码

class Solution {
public:
    int scoreOfParentheses(string S) {
        int s[55] = {0};
        vector<int> v(55, 0);
        int top = 0;
        int left = 0;
        int sum = 0;
        for (int i = 1; i < S.size(); ++i) {
            if (S[i] == '(') s[++top] = i;
            else {    
                left = s[top--];
                if (left == i-1) {
                    v[i] = 1;
                }
                else {
                    sum = 0;
                    for (int j = left; j < i; ++j) {
                        sum += v[j];
                        v[j] = 0;
                    }
                    v[i] = 2*sum;
                }
                
            }
        }
        return accumulate(v.begin(), v.end(), 0);
    }
};

以上是关于leetcode 856. Score of Parentheses的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 856. 括号的分数(Score of Parentheses)

856. Score of Parentheses

LC 856. Score of Parentheses

856. Score of Parentheses

力扣 每日一题 856. 括号的分数难度:中等(栈 / 思维计数&括号深度)

LeetCode 0856. 括号的分数