TikTok OA 面试真题解析:Score of Parentheses(括号字符串得分)

24次阅读
没有评论

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

The score of a balanced parentheses string is based on the following rules:

  • () 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

Example 4:

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

这道题要求根据括号字符串的递归定义计算得分:最基础的“()”得 1,两个平衡括号串相连时得分相加,外面再包一层括号时得分翻倍。常见做法是使用栈或递归 / 迭代的计分思路,遍历字符串时根据括号结构累加局部贡献;也可以用深度统计法理解每一对“()”在不同嵌套层级上的权重。示例中“()”为 1,“(())”为 2,“()()”为 2,“(()(()))”为 6,核心就是正确处理嵌套与拼接两种结构。

正文完
 0