作者: 负雪明烛
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. R语言中的正则表达式(转载:http://blog.csdn.net/duqi_yc/article/details/9817243)

    转载:http://blog.csdn.net/duqi_yc/article/details/9817243 目录 Table of Contents 1 正则表达式简介 2 字符数统计和字符翻译 ...

  2. SpringCloud微服务实战——搭建企业级开发框架(二十八):扩展MybatisPlus插件DataPermissionInterceptor实现数据权限控制

    一套完整的系统权限需要支持功能权限和数据权限,前面介绍了系统通过RBAC的权限模型来实现功能的权限控制,这里我们来介绍,通过扩展Mybatis-Plus的插件DataPermissionInterce ...

  3. java中的Arrays类

    今天刚接触了数组,学到了几个比较常用的方法 Fill方法:给数组赋值 sort方法:给数组升序 equals方法:比较数组中元素 值是否相等 binarySearch方法:对排序好的数组进行二分查找法 ...

  4. Go语言核心36讲(Go语言实战与应用二十一)--学习笔记

    43 | bufio包中的数据类型(下) 在上一篇文章中,我提到了bufio包中的数据类型主要有Reader.Scanner.Writer和ReadWriter.并着重讲到了bufio.Reader类 ...

  5. Spring整合Mybatis报 java.lang.ClassNotFoundException:org.springframework.core.metrics.ApplicationStartup,即:spring的版本过高,采用RELEASE稳定版

    1.遇到的问题: 今天在弄spring整合mybatis的时候遇到一个小问题,如图所示: 简单来说:就是我的spring的xml文件没找到,我就奇了怪了,我所有的配置都没问题啊! 我pom.xml配置 ...

  6. JavaScript获取html表单值验证后跳转网页中的关键点

    关键代码: 1.表单部分 <form action="Depart.jsp" name="myform" method="post" ...

  7. Scala和Java的List集合互相转换

    import java.util import scala.collection.mutable /** * 集合互相转换 */ object ScalaToJava { def main(args: ...

  8. 大数据学习day33----spark13-----1.两种方式管理偏移量并将偏移量写入redis 2. MySQL事务的测试 3.利用MySQL事务实现数据统计的ExactlyOnce(sql语句中出现相同key时如何进行累加(此处时出现相同的单词))4 将数据写入kafka

    1.两种方式管理偏移量并将偏移量写入redis (1)第一种:rdd的形式 一般是使用这种直连的方式,但其缺点是没法调用一些更加高级的api,如窗口操作.如果想更加精确的控制偏移量,就使用这种方式 代 ...

  9. OpenStack之三: 安装MySQL,rabbitmq, memcached

    官网地址:https://docs.openstack.org/install-guide/environment-sql-database-rdo.html #:安装mysql [root@mysq ...

  10. 【编程思想】【设计模式】【行为模式Behavioral】registry

    Python版 https://github.com/faif/python-patterns/blob/master/behavioral/registry.py #!/usr/bin/env py ...