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);
    }
};
posted on 2018-06-24 14:40  Beserious  阅读(400)  评论(0编辑  收藏  举报