Score LeetCode 856. brackets (Score of Parentheses)

856. brackets score
856. Score of Parentheses

Title Description
Given a balanced parenthesis string S, the string score is calculated by the following rules:

  • () 1 point.
  • A + B AB points obtained, wherein A and B are balanced parentheses string.
  • (A) 2 * A points obtained, wherein A is balanced parentheses string.

LeetCode856. Score of Parentheses中等

Example 1:

Input: "()"
Output: 1

Example 2:

Input: "(())"
Output: 2

Example 3:

Input: "() ()"
Output: 2

Example 4:

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

prompt:

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

Java implementation

import java.util.Stack;

class Solution {
    public int scoreOfParentheses(String S) {
        int cur = 0;
        Stack<Integer> stack = new Stack<>();
        for (char c : S.toCharArray()) {
            if (c == '(') {
                stack.push(cur);
                cur = 0;
            } else {
                cur = stack.pop() + Math.max(cur * 2, 1);
            }
        }
        return cur;
    }
}

Reference material

Guess you like

Origin www.cnblogs.com/hglibin/p/10988617.html
Recommended