小念子

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

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

 

解答:

使用count统计括号数量,遇左括号++,遇右括号--,当count==0时,说明可以进行计算

若此时字符串长度是2,则分数是1,即()

若此时字符串长度超过2,则脱去开始和结尾的括号,结果应是2*scoreOfParentheses(S.substring(start + 1, i))

最后的结果进行累加即可

    public int scoreOfParentheses(String S) {
        if (S == null || S.length() == 0) {
            return 0;
        }
        int count = 0; // 统计括号数量
        int start = 0;
        int res = 0;
        for (int i = 0; i < S.length(); ++i) {
            if (S.charAt(i) == '(') {
                count++;
            } else {
                count--;
            }
            if (count == 0) {
                if ((i - start) == 1) {
                    res += 1;
                } else {
                    res = res + 2 * scoreOfParentheses(S.substring(start + 1, i));
                }
                start = i + 1;
            }
        }
        return res;
    } 

 

posted on 2020-11-09 20:36  小念子  阅读(122)  评论(0编辑  收藏  举报