1. 程式人生 > 實用技巧 >856. 括號的分數

856. 括號的分數

給定一個平衡括號字串 S,按下述規則計算該字串的分數:

() 得 1 分。
AB 得 A + B 分,其中 A 和 B 是平衡括號字串。
(A) 得 2 * A 分,其中 A 是平衡括號字串。

示例 1:

輸入: "()"
輸出: 1

示例 2:

輸入: "(())"
輸出: 2

示例 3:

輸入: "()()"
輸出: 2

示例 4:

輸入: "(()(()))"
輸出: 6 

解題思路:

  括號代表深度,1, 2, 4, 8,...,2n方。

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

  

提示:

S 是平衡括號字串,且只含有 ( 和 ) 。
2 <= S.length <= 50

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/score-of-parentheses
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。