递归专题1
Given a balanced parentheses string
S
, compute the score of the string based on the following rule:
()
has score 1AB
has scoreA + B
, where A and B are balanced parentheses strings.(A)
has score2 * A
, where A is a balanced parentheses string.Example 1:
Input: "()" Output: 1Example 2:
Input: "(())" Output: 2Example 3:
Input: "()()" Output: 2Example 4:
Input: "(()(()))" Output: 6Note:
S
is a balanced parentheses string, containing only(
and)
.2 <= S.length <= 50
public static int scoreOfParentheses(String S) {
return score(S);
}
private static int score(String sub) {
if (sub.equals("()")) { //case ()
return 1;
}
int balanceBias = 0;
for (int i = 0; i < sub.length(); i++) {
if (sub.charAt(i) == '(') balanceBias++;
if (sub.charAt(i) == ')') balanceBias--;
//case (A)+(B),但是(A)这个形式的组合也走这里,所以加一个判断
if (balanceBias == 0 && !sub.equals(sub.substring(0,i+1)))
return score(sub.substring(0,i+1)) + score(sub.substring(i+1,sub.length()));
}
//case (A)
return 2*score(sub.substring(1, sub.length()-1));
}