1. 程式人生 > >Score of Parentheses(856)

Score of Parentheses(856)

856— Score of Parentheses

Given a balanced parentheses string S, compute the score of the string based on the following rule:

  • “()” has score 1
  • “AB” has score A + B, where A and B are balanced parentheses strings.
  • “(A)” has score 2 * A, where A is a balanced parentheses string.

Example 1:

Input: “()”
Output: 1

Example 2:

Input: “(())”
Output: 2

Example 3:

Input: “()()”
Output: 2

Example 4:

Input: “(()(()))”
Output: 6

C++程式碼:

class Solution {
public:
    int scoreOfParentheses(string S) {
      return helper(S,0,S.length()-1);
} private: int helper(string &s,int l,int r) { if(r - l == 1) return 1; //”()“情況 int count = 0; for (int i = l; i < r; i++) { //注意迴圈到i=r-1 if(s[i] == '(') count ++; else if(s[i] == ')') count--; if(count == 0) return helper(
s,l,i) + helper(s,i+1,r); //“AB”的情況; } return 2*helper(s,l+1,r-1); //“(A)”的情況 } };

Complexity Analysis:

Time complexity : O(n)~O(n^2). 最好的情況:“()()()”; 最壞的情況:“((()))”
Space complexity : O(n).

思路:

  • 遞迴的思想
  • 關鍵:如何判斷括號匹配情況,是否是平衡的. 當count等於0時平衡, 當count最終不等於0,即“(A)”的情況,如何處理.

思路2:

  • 只算每個“()”外層括號數k,為 2 k 1 2^{k-1}

例如“( () ( () () ) )”, 即 2 1 + 2 2 + 2 2 = 10 2^{1}+2^{2} +2^{2} =10

Complexity Analysis:

Time complexity : O(n). 遍歷字串一次
Space complexity : O(1).

C++程式碼:

class Solution {
public:
  int scoreOfParentheses(string S) {
    int count = 1, ans = 0;
    for (int i = 1; i < S.length(); i++) {
      if(S[i] == '(') count ++;
      if(S[i] == ')'){
        if(S[i-1] == '('){        //當出現“()”時
          ans += 1 << (count-1);
        }
        count --;
      }
    }
    return ans;
  }
};