返回介绍

solution / 0800-0899 / 0856.Score of Parentheses / README_EN

发布于 2024-06-17 01:03:33 字数 5057 浏览 0 评论 0 收藏 0

856. Score of Parentheses

中文文档

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.

Solutions

Solution 1: Counting

By observing, we find that () is the only structure that contributes to the score, and the outer parentheses just add some multipliers to this structure. So, we only need to focus on ().

We use $d$ to maintain the current depth of parentheses. For each (, we increase the depth by one, and for each ), we decrease the depth by one. When we encounter (), we add $2^d$ to the answer.

Let's take (()(())) as an example. We first find the two closed parentheses () inside, and then add the corresponding $2^d$ to the score. In fact, we are calculating the score of (()) + ((())).

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

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

The time complexity is $O(n)$, and the space complexity is $O(1)$. Here, $n$ is the length of the string.

Related problems about parentheses:

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
class Solution {
  public int scoreOfParentheses(String s) {
    int ans = 0, d = 0;
    for (int i = 0; i < s.length(); ++i) {
      if (s.charAt(i) == '(') {
        ++d;
      } else {
        --d;
        if (s.charAt(i - 1) == '(') {
          ans += 1 << d;
        }
      }
    }
    return ans;
  }
}
class Solution {
public:
  int scoreOfParentheses(string s) {
    int ans = 0, d = 0;
    for (int i = 0; i < s.size(); ++i) {
      if (s[i] == '(') {
        ++d;
      } else {
        --d;
        if (s[i - 1] == '(') {
          ans += 1 << d;
        }
      }
    }
    return ans;
  }
};
func scoreOfParentheses(s string) int {
  ans, d := 0, 0
  for i, c := range s {
    if c == '(' {
      d++
    } else {
      d--
      if s[i-1] == '(' {
        ans += 1 << d
      }
    }
  }
  return ans
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文