zoukankan      html  css  js  c++  java
  • 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);
        }
    };
    
  • 相关阅读:
    JPA与Hibernate的关系
    EJB里的问题解答
    EJB与JPA的关系
    EJB的魅惑来源
    EJB简介
    MyEclipse如何恢复删掉的文件
    EasyUI的功能树之扁平化
    EasyUI的功能树之异步树
    Spring AOP的日志记录
    简单理解IoC与DI
  • 原文地址:https://www.cnblogs.com/pk28/p/9220501.html
Copyright © 2011-2022 走看看