leetcode - 856. Score of Parentheses

发布时间:2024年01月17日

Description

Given a balanced parentheses string s, return the score of the string.

The score of a balanced parentheses string is 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: s = "()"
Output: 1

Example 2:

Input: s = "(())"
Output: 2

Example 3:

Input: s = "()()"
Output: 2

Constraints:

2 <= s.length <= 50
s consists of only '(' and ')'.
s is a balanced parentheses string.

Solution

Recursive

If it’s (, then find the matching ) and calculate the result in the middle.

Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( n ) o(n) o(n)

Stack

Solved after help.

Whenever there’s a (, put a 0 into the stack. And when there is ), start calculating. If the top element of the stack is 0, transform that 0 into 1, otherwise keep adding until we meet 0, which means we meet the matching ( for the current ), then multiplies the result by 2.

Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( n ) o(n) o(n)

Code

Recursive

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

        def helper(left: int, right: int) -> int:
            if left >= right:
                return 0
            i = left
            res = 0
            while i <= right:
                if s[i] == '(':
                    j = find_matching_index(i)
                    res_in_middle = helper(i + 1, j - 1)
                    if res_in_middle == 0:
                        res += 1
                    else:
                        res += 2 * res_in_middle
                    i = j + 1
            return res

        return helper(0, len(s) - 1)                    

Stack

class Solution:
    def scoreOfParentheses(self, s: str) -> int:
        stack = []
        for c in s:
            if c == '(':
                stack.append(0)
            else:
                if stack[-1] == 0:
                    stack[-1] = 1
                else:
                    cur_res = stack.pop()
                    while stack[-1] != 0:
                        cur_res += stack.pop()
                    stack[-1] = 2 * cur_res
        return sum(stack)
文章来源:https://blog.csdn.net/sinat_41679123/article/details/135639412
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。