
856. Score of Parentheses
发布日期:2021-05-09 02:51:25
浏览次数:22
分类:博客文章
本文共 1533 字,大约阅读时间需要 5 分钟。
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 strings
Example 1:
Input: "()"Output: 1Example 2:
Input: "(())"Output: 2Example 3:
Input: "()()"Output: 2Example 4:
Input: "(()(()))"Output: 6
Note:
S
is a balanced parentheses string, containing only(
and)
.2 <= S.length <= 50
Approach #1. DFS. [Java]
class Solution { public int scoreOfParentheses(String S) { return helper(S, 0, S.length() - 1); } public int helper(String S, int l, int r) { if (l + 1 == r) return 1; int b = 0; for (int i = l; i < r; ++i) { if (S.charAt(i) == '(') b++; else b--; if (b == 0) return helper(S, l, i) + helper(S, i+1, r); } return 2 * helper(S, l + 1, r - 1); }}
������
Approach #2: Stack. [Java]
class Solution { public int scoreOfParentheses2(String S) { boolean mode = true; int ret = 0; Stackstack = new Stack<>(); for (int i = 0; i < S.length(); ++i) { if (S.charAt(i) == ')' && mode) { ret += Math.pow(2, stack.size() - 1); mode = false; stack.pop(); } else if (S.charAt(i) == '(') { stack.push('('); mode = true; } else { stack.pop(); } } return ret; }}
������
发表评论
最新留言
做的很好,不错不错
[***.243.131.199]2025年04月30日 17时48分19秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Powershell中禁止执行脚本解决办法
2021-05-09
HTTP协议状态码详解(HTTP Status Code)
2021-05-09
OO_Unit2 多线程电梯总结
2021-05-09
04_Mysql配置文件(重要参数)
2021-05-09
python 序列化及其相关模块(json,pickle,shelve,xml)详解
2021-05-09
JavaSE总结
2021-05-09
手动造轮子——基于.NetCore的RPC框架DotNetCoreRpc
2021-05-09
Python IO编程
2021-05-09
CSS入门总结
2021-05-09
使用 TortoiseGit 时,报 Access denied 错误
2021-05-09
基于 HTML5 WebGL 的污水处理厂泵站自控系统
2021-05-09
[系列] Go gRPC 调试工具
2021-05-09
django-表单之模型表单渲染(六)
2021-05-09
c++之程序流程控制
2021-05-09
spring-boot-2.0.3之redis缓存实现,不是你想的那样哦!
2021-05-09
httprunner学习23-加解密
2021-05-09
有道云笔记 同步到我的博客园
2021-05-09