LeetCode 题解工作台

括号的分数

给定一个平衡括号字符串 S ,按下述规则计算该字符串的分数: () 得 1 分。 AB 得 A + B 分,其中 A 和 B 是平衡括号字符串。 (A) 得 2 * A 分,其中 A 是平衡括号字符串。 示例 1: 输入: "()" 输出: 1 示例 2: 输入: "(())" 输出: 2 示例 3…

category

2

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 栈·状态

bolt

答案摘要

我们通过观察发现,`()` 是唯一贡献分数的结构,外括号只是为该结构添加了一些乘数。所以我们只需要关心 `()`。 我们用 维护当前括号的深度,对于每个 `(`,我们将深度加一,对于每个 `)`,我们将深度减一。当我们遇到 `()` 时,我们将 加到答案中。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个平衡括号字符串 S,按下述规则计算该字符串的分数:

  • () 得 1 分。
  • AB 得 A + B 分,其中 A 和 B 是平衡括号字符串。
  • (A) 得 2 * A 分,其中 A 是平衡括号字符串。

 

示例 1:

输入: "()"
输出: 1

示例 2:

输入: "(())"
输出: 2

示例 3:

输入: "()()"
输出: 2

示例 4:

输入: "(()(()))"
输出: 6

 

提示:

  1. S 是平衡括号字符串,且只含有 ( 和 ) 。
  2. 2 <= S.length <= 50
lightbulb

解题思路

方法一:计数

我们通过观察发现,() 是唯一贡献分数的结构,外括号只是为该结构添加了一些乘数。所以我们只需要关心 ()

我们用 dd 维护当前括号的深度,对于每个 (,我们将深度加一,对于每个 ),我们将深度减一。当我们遇到 () 时,我们将 2d2^d 加到答案中。

我们举个实际的例子,以 (()(())) 为例,我们首先找到内部两个闭合括号 (),然后将分数加上对应的 2d2^d。实际上,我们是在计算 (()) + ((())) 的分数。

( ( ) ( ( ) ) )
  ^ ^   ^ ^

( ( ) ) + ( ( ( ) ) )
  ^ ^         ^ ^

时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。其中 nn 是字符串的长度。

括号相关类型题:

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def scoreOfParentheses(self, s: str) -> int:
        ans = d = 0
        for i, c in enumerate(s):
            if c == '(':
                d += 1
            else:
                d -= 1
                if s[i - 1] == '(':
                    ans += 1 << d
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for an efficient stack-based solution to manage nested structures.

  • question_mark

    Evaluate how the candidate handles multiple nested parentheses and their score computation.

  • question_mark

    Focus on correct state management using the stack, ensuring the solution works for all string lengths.

warning

常见陷阱

外企场景
  • error

    Mismanaging nested parentheses by not properly doubling the inner score.

  • error

    Forgetting to add the scores when encountering non-nested parentheses like '()()'.

  • error

    Incorrect stack operations that lead to incorrect score accumulation.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Modify the problem to handle non-balanced parentheses strings and test for validity.

  • arrow_right_alt

    Optimize the solution to handle larger strings by managing stack size more effectively.

  • arrow_right_alt

    Consider variations where parentheses are nested with different operations or values.

help

常见问题

外企场景

括号的分数题解:栈·状态 | LeetCode #856 中等