leetcode講解--856. Score of Parentheses

題目

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

() 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.code

Example 1:leetcode

Input: "()"
Output: 1

Example 2:get

Input: "(())"
Output: 2

Example 3:string

Input: "()()"
Output: 2

Example 4:io

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

Note:class

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

題目地址變量

講解

這道題分類都有點難,能夠算在智力題裏面。主要是要理解一個套路:sed

"(()(()))" -> "(())" + "((()))" = 2 + 4

這樣就會發現,能夠維護一個層數變量,而後遍歷的時候,遇到'('就加一,遇到")"就減一,遇到"()"這一對,就至關於找到了一組。而後把找到的全部組相加就好了。遍歷

java代碼

class Solution {
    public int scoreOfParentheses(String S) {
        int d = -1;
        int result = 0;
        for(int i=0;i<S.length();i++){
            d += S.charAt(i)=='('?1:-1;
            if(S.charAt(i)=='(' && S.charAt(i+1)==')'){
                result += 1 << d;
            }
        }
        return result;
    }
}
相關文章
相關標籤/搜索