作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/score-of-parentheses/description/

题目描述

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.

Example 1:

Input: "()"
Output: 1

Example 2:

Input: "(())"
Output: 2

Example 3:

Input: "()()"
Output: 2

Example 4:

Input: "(()(()))"
Output: 6

Note:

  1. S is a balanced parentheses string, containing only ( and ).
  2. 2 <= S.length <= 50

题目大意

括号匹配的题目,但是这个匹配题目给定了条件:如果是()得1分,如果AB形式得2分,如果(A)分数是2×A.求最终多少分。

解题方法

括号匹配的题目一般要用到栈,这个题也是。我们用栈保存两样东西:一是左括号(,二是得分。这样我们在遇到)返回的时候,可以直接判断栈里面是左括号还是得分。如果是左括号(,那么得分是1,放入栈中。如果是得分,那么我们需要一直向前求和直到找到左括号为止,然后把这个得分×2,放入栈中。

由于题目给的是符合要求的括号匹配对,那么栈里面最后应该只剩下一个元素了,就是最终得分。

Python代码如下:

class Solution(object):
def scoreOfParentheses(self, S):
"""
:type S: str
:rtype: int
"""
stack = []
score = 0
for c in S:
if c == '(':
stack.append("(")
else:
tc = stack[-1]
if tc == '(':
stack.pop()
stack.append(1)
else:
num = 0
while stack[-1] != '(':
num += stack.pop()
stack.pop()
stack.append(num * 2)
return sum(stack)

如果一个栈里面只放数值的话,那么,我们可以把遇到的左括号变成0放到栈里面。我们遇到右括号的时候,把前面的数字乘以2重新放入栈的末尾,但是()是直接放入1的。为了防止栈为空,那么在栈开始的时候放入一个0,当把栈过了一遍之后,剩余的数字就是所求。

用官方例子说明:

For example, when counting (()(())), our stack will look like this:

[0, 0] after parsing (
[0, 0, 0] after (
[0, 1] after )
[0, 1, 0] after (
[0, 1, 0, 0] after (
[0, 1, 1] after )
[0, 3] after )
[6] after )

python代码如下:

class Solution(object):
def scoreOfParentheses(self, S):
"""
:type S: str
:rtype: int
"""
stack = [0]
score = 0
for c in S:
if c == '(':
stack.append(0)
else:
v = stack.pop()
stack[-1] += max(v * 2, 1)
return sum(stack)

递归

这个递归解法,我们使用的是从两头向中间的策略。如果找到的了()返回1,否则向中间找有没有提前匹配好的,这个如果存在就是AB形式,返回的是A+B。如果不存在的话,那说明是(A)形式,就返回2×A.

注意,在找AB的时候,i从l开始只能循环到r - 1,最后的一个括号不能进行匹配。

C++代码如下:

class Solution {
public:
int scoreOfParentheses(string S) {
return helper(S, 0, S.size() - 1);
}
private:
int helper(string& s, int l, int r) {//[l, r]
if (r - l == 1) return 1;
int count = 0;
for (int i = l; i < r; i++) {
if (s[i] == '(')
count++;
else
count--;
if (count == 0) {
return helper(s, l, i) + helper(s, i + 1, r);
}
}
return helper(s, l + 1, r - 1) * 2;
}
};

计数

我们从左到右去统计,开放的'('数目为d,如果遇到一个(就意味着里面的()要加倍。当我们遇到()的时候,需要增加2^(d-1)到结果里面。这个方法只关注()

C++代码如下:

class Solution {
public:
int scoreOfParentheses(string S) {
int res = 0, val = 0;
for (int i = 0; i < S.size(); i ++) {
if (S[i] == '(')
val++;
else{
val--;
if (S[i - 1] == '(')
res += 1 << val;
}
}
return res;
}
};

日期

2018 年 12 月 11 日 —— 双十一已经过去一个月了,真快啊。。

【LeetCode】856. Score of Parentheses 解题报告(Python & C++)的更多相关文章

  1. Leetcode 856. Score of Parentheses 括号得分(栈)

    Leetcode 856. Score of Parentheses 括号得分(栈) 题目描述 字符串S包含平衡的括号(即左右必定匹配),使用下面的规则计算得分 () 得1分 AB 得A+B的分,比如 ...

  2. LeetCode 856. Score of Parentheses 括号的分数

    其实是这道题的变式(某港带同学的C/C++作业) 增加一点难度,输入的S不一定为平衡的,需要自己判断是否平衡,若不平衡输出为0. 题目描述 Given a parentheses string s, ...

  3. 【LeetCode】62. Unique Paths 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/unique-pa ...

  4. 【LeetCode】376. Wiggle Subsequence 解题报告(Python)

    [LeetCode]376. Wiggle Subsequence 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.c ...

  5. 【LeetCode】649. Dota2 Senate 解题报告(Python)

    [LeetCode]649. Dota2 Senate 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地 ...

  6. 【LeetCode】911. Online Election 解题报告(Python)

    [LeetCode]911. Online Election 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ ...

  7. 【LeetCode】886. Possible Bipartition 解题报告(Python)

    [LeetCode]886. Possible Bipartition 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu ...

  8. 【LeetCode】36. Valid Sudoku 解题报告(Python)

    [LeetCode]36. Valid Sudoku 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址 ...

  9. 【LeetCode】870. Advantage Shuffle 解题报告(Python)

    [LeetCode]870. Advantage Shuffle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn ...

随机推荐

  1. annovar 注释除人类以外的SNP

    1. 准备文件: ref.fa ref.gtf或者gff3,最好是gtf3,可将gff3转化为gtf sample.vcf 2. 用gff3ToGenePred与gtfToGenePred工具将gtf ...

  2. R语言与医学统计图形-【18】ggplot2几何对象汇总

    ggplot2绘图系统--几何对象汇总 前面介绍了常见的几种基本的几何对象,并且介绍了scale.stat等其他要素.后续将介绍position.themes.coord和faceting等函数. 这 ...

  3. R语言与医学统计图形-【11】ggplot2几何对象之散点图

    ggplot2绘图系统--几何对象之散点图 以geom开头的函数超过30个.几何对象和标度函数scale密不可分.只有在aes中传入某个变量,scale才能发挥作用. 所谓标度scale,就是图形遥控 ...

  4. EXCEL-如何在excel中对图片进行批量排版

    新建EXCEL->导入图片->如果每张图高度为33个单元格,共计10张图,那么将最后边的那张图(即正对着你的那一张)剪切粘贴到33*9行第一个单元格处->按F5定位"对象& ...

  5. C++ 中的多重继承的问题

    如何正确使用C++多重继承 BY R12F · PUBLISHED 2011年06月17日 · UPDATED 2012年03月11日   原创文章,转载请注明:转载自Soul Apogee本文链接地 ...

  6. 巩固java第四天

    巩固内容: HTML 元素 HTML 文档由 HTML 元素定义. HTML 元素 开始标签 * 元素内容 结束标签 * <p> 这是一个段落 </p> <a href= ...

  7. addict, address, adequate.四级

    addict addiction – a biopsychosocial [生物社会心理学的 bio-psycho-social] disorder characterized by persiste ...

  8. day10 ajax的基本使用

    day10 ajax的基本使用 今日内容 字段参数之choices(重要) 多对多的三种创建方式 MTV与MVC理论 ajax语法结构(固定的) 请求参数contentType ajax如何传文件及j ...

  9. ORACLE 服务器验证

    位于$ORACLE_HOME/network/admin/sqlnet.oraSQLNET.AUTHENTICATION_SERVICES=none|all|ntsnone:关闭操作系统认证,只能密码 ...

  10. mysql explain using filesort

    创建表,字段tid上无索引(mysql 5.7) CREATE TABLE `test` ( `tid` int(11) DEFAULT NULL, `tname` varchar(12) DEFAU ...