zoukankan      html  css  js  c++  java
  • 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 strings

    Example 1:

    Input: "()"
    Output: 1
    

    Example 2:

    Input: "(())"
    Output: 2
    

    Example 3:

    Input: "()()"
    Output: 2
    

    Example 4:

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

    Note:

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

    Approach #1. DFS. [Java]

    class Solution {
        public int scoreOfParentheses(String S) {
            return helper(S, 0, S.length() - 1);
        }
        
        public int helper(String S, int l, int r) {
            if (l + 1 == r) return 1;
            int b = 0;
            for (int i = l; i < r; ++i) {
                if (S.charAt(i) == '(') b++;
                else b--;
                if (b == 0) return helper(S, l, i) + helper(S, i+1, r);
            }
            return 2 * helper(S, l + 1, r - 1);
        }
    
    }
    

      

    Approach #2: Stack. [Java]

    class Solution {
        public int scoreOfParentheses2(String S) {
            boolean mode = true;
            int ret = 0;
            Stack<Character> stack = new Stack<>();
            for (int i = 0; i < S.length(); ++i) {
                if (S.charAt(i) == ')' && mode) {
                    ret += Math.pow(2, stack.size() - 1);
                    mode = false;
                    stack.pop();
                } else if (S.charAt(i) == '(') {
                    stack.push('(');
                    mode = true;
                } else {
                    stack.pop();
                }
            }
            return ret;
        }
    
    }
    

      

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    P1371 NOI元丹
    最小费用最大流
    City Game UVALive
    P2389 电脑班的裁员
    P1959 遗址_NOI导刊2009普及(6)
    P2700 逐个击破
    P1630 求和
    P4310 绝世好题
    java常用类:1。包装类(以Integer类为例)2.String类 3.StringBuffer
    java异常,异常处理,异常类 关键字:throws 和 throw 自定义的异常类
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10793208.html
Copyright © 2011-2022 走看看