JAVA程序设计:括号的分数(LeetCode:856)

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

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

示例 1:

输入: "()"
输出: 1
示例 2:

输入: "(())"
输出: 2
示例 3:

输入: "()()"
输出: 2
示例 4:

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

提示:

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

思路:做多了就会发现,对于嵌套类的问题,基本就是递归了,对于本题也是一样,考察的明显是简单的递归调用,顺便处理下括号组成的分数。

class Solution {
    public int scoreOfParentheses(String S) {
    	
    	if(S.length()<2) return 0;
    	if(S.length()==2) return 1;
    	
    	int sum=0;
    	
    	for(int i=0;i<S.length();i++) {
    		if(S.charAt(i)=='(') {
    			int j=i,bal=0;
    			for(j=i;j<S.length();j++) {
    				if(S.charAt(j)=='(') bal++;
    				if(S.charAt(j)==')') bal--;
    				if(bal==0) {
    					int now=scoreOfParentheses(S.substring(i+1, j));
    					sum+=(now==0?1:now*2);
    					break;
    				}
    			}
    			i=j;
    		}
    	}
    	
    	return sum;
    }
}
扫描二维码关注公众号,回复: 11154655 查看本文章
原创文章 1111 获赞 194 访问量 25万+

猜你喜欢

转载自blog.csdn.net/haut_ykc/article/details/105572785