【LeetCode】856. Score of Parentheses 解题报告(Python & C++)
作者: 负雪明烛
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 1AB
has scoreA + B
, where A and B are balanced parentheses strings.(A)
has score2 * 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:
- S is a balanced parentheses string, containing only ( and ).
- 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++)的更多相关文章
- Leetcode 856. Score of Parentheses 括号得分(栈)
Leetcode 856. Score of Parentheses 括号得分(栈) 题目描述 字符串S包含平衡的括号(即左右必定匹配),使用下面的规则计算得分 () 得1分 AB 得A+B的分,比如 ...
- LeetCode 856. Score of Parentheses 括号的分数
其实是这道题的变式(某港带同学的C/C++作业) 增加一点难度,输入的S不一定为平衡的,需要自己判断是否平衡,若不平衡输出为0. 题目描述 Given a parentheses string s, ...
- 【LeetCode】62. Unique Paths 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/unique-pa ...
- 【LeetCode】376. Wiggle Subsequence 解题报告(Python)
[LeetCode]376. Wiggle Subsequence 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.c ...
- 【LeetCode】649. Dota2 Senate 解题报告(Python)
[LeetCode]649. Dota2 Senate 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地 ...
- 【LeetCode】911. Online Election 解题报告(Python)
[LeetCode]911. Online Election 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ ...
- 【LeetCode】886. Possible Bipartition 解题报告(Python)
[LeetCode]886. Possible Bipartition 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu ...
- 【LeetCode】36. Valid Sudoku 解题报告(Python)
[LeetCode]36. Valid Sudoku 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址 ...
- 【LeetCode】870. Advantage Shuffle 解题报告(Python)
[LeetCode]870. Advantage Shuffle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn ...
随机推荐
- 基因组共线性分析工具MCScanX
软件简介 MCScanX工具集对MCScan算法进行了调整,用于检测共线性和同线性区域,还增加了可视化和下游分析..MCscanX有三个核心工具,以及12个下游分析工具. 软件安装 进入官网http: ...
- Freeswitch 安装爬坑记录1
2 Freeswitch的安装 2.1 准备工作 服务器安装CentOS 因为是内部环境,可以关闭一些防火墙设置,保证不会因为网络限制而不能连接 关闭防火墙 查看防火墙 systemctl statu ...
- JVM结构详解
JVM 结构详解 JVM 结构图 程序计数器(PC 寄存器) 程序计数器的定义 程序计数器是一块较小的内存空间,是当前线程正在执行的那条字节码指令的地址.若当前线程正在执行的是一个本地方法,那么此时程 ...
- Shell学习(九)——chattr与lsattr命令详解
有时候你发现用root权限都不能修改某个文件,大部分原因是曾经用chattr命令锁定该文件了.chattr命令的作用很大,其中一些功能是由Linux内核版本来支持的,不过现在生产绝大部分跑的linux ...
- Linux:cp -rp
cp -rp[原文件或目录] [目标文件或目录] -r 复制目录 - p 保留文件属性 范例: cp -r /yy/k /yy/u /mm 复制目录u和目录k到目录mm中 cp -r /yy/ ...
- Function overloading and const keyword
Predict the output of following C++ program. 1 #include<iostream> 2 using namespace std; 3 4 c ...
- Dubbo消费者异步调用Future使用
Dubbo的四大组件工作原理图,其中消费者调用提供者采用的是同步调用方式.消费者对于提供者的调用,也可以采用异步方式进行调用.异步调用一般应用于提供者提供的是耗时性IO服务 一.Future异步执行原 ...
- java关键字volatile内存语义详细分析
volatile变量自身具有下列特性. 1.可见性.对一个volatile变量的读,总是能看到(任意线程)对这个volatile变量最后的写 入. · 2.原子性:对任意单个volatile变量的读/ ...
- 【C/C++】字符数组:char,char*,char a[], char *a[], char **s 的区别与联系/const char*和char*的区别
一.char,char*,char a[], char *a[], char **s 的区别与联系 C语言中的字符串是字符数组,可以像处理普通数组一样处理字符串. 可以理解为在内存中连续存储的字符. ...
- 使用匿名内部类和lamda的方式创建线程
1.匿名内部类的方式 1 /** 2 *匿名内部类的方式启动线程 3 */ 4 public class T2 { 5 public static void main(String[] args) { ...