解法一:递归

先按照规则2划分成多个子串,符合规则1的就为1,符合规则3就解开一层括号,进一步递归求解。

  1. class Solution {
  2. public int scoreOfParentheses(String S) {
  3. return sum(S, 0, S.length() - 1);
  4. }
  5. private int sum(String S, int left, int right) {
  6. int begin = left;
  7. int ans = 0;
  8. int count = 0;
  9. for (int i = left; i <= right; ++i) {
  10. if (S.charAt(i) == '(') {
  11. ++count;
  12. } else {
  13. --count;
  14. }
  15. // 规则2
  16. if (count == 0) {
  17. // 规则1
  18. if (i == begin + 1) {
  19. ++ans;
  20. } else { // 规则3
  21. ans += sum(S, begin + 1, i - 1) * 2;
  22. }
  23. begin = i + 1;
  24. }
  25. }
  26. return ans;
  27. }
  28. }

解法二:栈

官方题解:https://leetcode-cn.com/problems/score-of-parentheses/solution/gua-hao-de-fen-shu-by-leetcode/
遇到(就入栈,遇到)就出栈,分规则1和规则3两种情况计算数值。

  1. class Solution {
  2. public int scoreOfParentheses(String S) {
  3. Deque<Integer> stack = new LinkedList<>();
  4. int u, v;
  5. // 栈底存储最终答案
  6. stack.push(0);
  7. for (char ch : S.toCharArray()) {
  8. if (ch == '(') {
  9. stack.push(0);
  10. } else {
  11. u = stack.pop();
  12. v = stack.pop() + Math.max(u * 2, 1);
  13. stack.push(v);
  14. }
  15. }
  16. return stack.pop();
  17. }
  18. }

解法三:统计()的个数

根据当前括号嵌套深度计算该()展开后的数值。参考官方题解。

  1. class Solution {
  2. public int scoreOfParentheses(String S) {
  3. int ans = 0;
  4. // 括号嵌套深度
  5. int depth = 0;
  6. for (int i = 0; i < S.length(); ++i) {
  7. if (S.charAt(i) == '(') {
  8. ++depth;
  9. } else {
  10. --depth;
  11. if (S.charAt(i - 1) == '(') {
  12. ans += 1 << depth;
  13. }
  14. }
  15. }
  16. return ans;
  17. }
  18. }