LeetCode856. 括号的分数(Java实现)

LeetCode856. 括号的分数(Java实现)_第1张图片

public int scoreOfParentheses(String S) {
    Stack<Integer> stack = new Stack();
    stack.push(0); // The score of the current frame

    for (char c: S.toCharArray()) {
        if (c == '(')
            stack.push(0);
        else {
            int v = stack.pop();
            int w = stack.pop();
            stack.push(w + Math.max(2 * v, 1));
        }
    }

    return stack.pop();
}

数学方法

class Solution {

    public int scoreOfParentheses(String S) {
        int ans = 0, bal = 0;  //bal表示深度
        for (int i = 0; i < S.length(); ++i) {
            if (S.charAt(i) == '(') {   //遇到左括号,深度加1
                bal++;                  
            } else {                    //遇到右括号,深度减1
                bal--;
                if (S.charAt(i-1) == '(')  //前一位是左括号,则累加到ans上
                    ans += 1 << bal;
            }
        }

        return ans;
    }
}

你可能感兴趣的:(力扣,笔记,栈,stack,算法)