查看: 996| 回复: 0
跳转到指定楼层
上一主题 下一主题
收起左侧

[Leetcode] 856. Score of Parentheses

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
本帖最后由 HiAG3 于 2019-9-21 12:19 编辑

Problem
Given a balanced parentheses string S, compute the score of the string 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.

这道题一开始看leet code上的article没有特别懂,和朋友讨论了后思路如下,想和大家分享,附了python solution在最后,求大米~~

这道题是看到右括号就要开始计算,last in first out,所以这里我们用stack。问题是,我们什么时候值是1,什么时候算加法or乘法

step1: 看到左括号就push一个0进stack里,看到右括号就开始算。pop出来的是0的话,就是代表这个右括号前面是左括号,rule1,() = 0。
step2: 每次计算之后,都把结果存在上一层的括号里,这也是符合rule2的。这样的话,pop时候的元素,就是这个括号里面的值。
step3: 如果等于0, 就是空括号,rule1。如果大于0,就用rule3计算把里面的值*2 。

一开始stack中有个0,我的理解就是我们最后要的结果就是相当于在原来的式子外面套一层括号,原来的式子的结果存在我们加的这个括号里。

python solution

  1. def parentheses_score(parestr):
  2.     """Evaluate the score of a balanced parebtheses string.

  3.     () has score 1
  4.     AB has score A + B, where A and B are balanced parentheses strings.
  5.     (A) has score 2 * A, where A is a balanced parentheses string.
  6.     """
  7.     stack = [0]
  8.     for i in parestr:
  9.         if i == "(":
  10.             stack.append(0)
  11.         else:
  12.             top = stack.pop()
  13.             if top == 0:
  14.                 stack[-1] += 1
  15.             else:
  16.                 stack[-1] += top * 2
  17.     return stack[0]

  18. # time O(n)
  19. # space O(n)
复制代码


上一篇:leetcode 937 求助 python
下一篇:请问R怎么安装lightgbm包呀
您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表