首页 > 其他 > 详细

LeetCode 856. 括号的分数(Score of Parentheses)

时间:2019-06-07 17:37:24      阅读:206      评论:0      收藏:0      [点我收藏+]

856. 括号的分数
856. Score of Parentheses

题目描述
给定一个平衡括号字符串?S,按下述规则计算该字符串的分数:

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

LeetCode856. Score of Parentheses中等

示例 1:

输入: "()"
输出: 1

示例 2:

输入: "(())"
输出: 2

示例?3:

输入: "()()"
输出: 2

示例?4:

输入: "(()(()))"
输出: 6

提示:

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

Java 实现

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;
    }
}

参考资料

LeetCode 856. 括号的分数(Score of Parentheses)

原文:https://www.cnblogs.com/hglibin/p/10988617.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!