1. Recursion

class Solution:
    def scoreOfParentheses(self, s: str) -> int:
        def dfs(l, r):
            res = bal = 0
            start = l
            for i in range(l, r):
                if s[i] == '(':
                    bal += 1
                else:
                    bal -= 1
                if bal == 0:
                    if i - start == 1:
                        res += 1
                    else:
                        res += 2 * dfs(start + 1, i)
                    start = i + 1
            return res

        return dfs(0, len(s))

Time & Space Complexity

  • Time complexity: O(n2)O(n ^ 2)
  • Space complexity: O(n)O(n) for recursion stack.

Where nn is the length of the string ss.


2. Stack

class Solution:
    def scoreOfParentheses(self, s: str) -> int:
        stack = [0]
        for c in s:
            if c == '(':
                stack.append(0)
            else:
                cur = stack.pop()
                stack[-1] += max(2 * cur, 1)
        return stack[-1]

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(n)O(n)

Where nn is the length of the string ss.


3. Iteration

class Solution:
    def scoreOfParentheses(self, s: str) -> int:
        res = depth = 0
        for i in range(len(s)):
            if s[i] == '(':
                depth += 1
            else:
                depth -= 1
                if s[i - 1] == '(':
                    res += 1 << depth
        return res

Time & Space Complexity

  • Time complexity: O(n)O(n)
  • Space complexity: O(1)O(1) extra space.

Where nn is the length of the string ss.