【LeetCode】921. Minimum Add to Make Parentheses Valid 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址: https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/
题目描述
Given a string S of ‘(’ and ‘)’ parentheses, we add the minimum number of parentheses ( ‘(’ or ‘)’, and in any positions ) so that the resulting parentheses string is valid.
Formally, a parentheses string is valid if and only if:
- It is the empty string, or
- It can be written as
AB
(A
concatenated withB
), whereA
andB
are valid strings, or - It can be written as
(A)
, whereA
is a valid string.
Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.
Example 1:
Input: "())"
Output: 1
Example 2:
Input: "((("
Output: 3
Example 3:
Input: "()"
Output: 0
Example 4:
Input: "()))(("
Output: 4
Note:
- S.length <= 1000
- S only consists of ‘(’ and ‘)’ characters.
题目大意
求最少添加几个括号才能使得整个表达式是合法的括号表达式。
解题方法
遇到括号匹配题一般想到用栈。这题也不例外。
同样是对字符串进行一次遍历,如果遍历到的位置是左括号,那么要进行判断:
- 如果栈顶是右括号,那么说明判断前面字符串缺少了几个括号
- 否则,需要直接进栈
如果遍历到的位置是右括号,那么直接进栈。
我花了半个小时才把这个题做出来啊,错误的地方就在于左括号的判断上。第一,判断前面缺少几个括号的时候,我把栈所有的元素全部退栈了,这样就错误了,因为可能前面部分匹配,再往前的左括号需要等待后面的右括号来了之后才能判断。所以,这个问题的解决方法是如果cnt == 0,就不再退栈了。第二,我把stack.append(’(’)写错位置了,事实上,只要出现新的左括号,这个左括号一定进栈。由于我太愚蠢了,把进栈这步放在了对栈的判断里面,这样就导致了不符合栈的判断条件的地方就没把左括号放进去。。这个是不应该犯的错误。
时间复杂度是O(N),空间复杂度是O(N)。
class Solution(object):
def minAddToMakeValid(self, S):
"""
:type S: str
:rtype: int
"""
if not S: return 0
stack = []
res = 0
for i, s in enumerate(S):
if '(' == s:
if stack and (stack[-1] == ')'):
cnt = 0
while stack:
if stack.pop() == ')':
cnt -= 1
else:
cnt += 1
if cnt == 0:
break
res += abs(cnt)
stack.append('(')
else:
stack.append(')')
cnt = 0
while stack:
if stack.pop() == ')':
cnt -= 1
else:
cnt += 1
res += abs(cnt)
return res
二刷使用了更简单的方法,直接把左括号进栈,遇到右括号时,如果栈里有左括号就弹出,否则需要加上右括号的个数。最后还要加上栈里面左括号的个数。
class Solution(object):
def minAddToMakeValid(self, S):
"""
:type S: str
:rtype: int
"""
res = 0
stack = []
for c in S:
if c == '(':
stack.append('(')
else:
if stack:
stack.pop()
else:
res += 1
return res + len(stack)
C++代码还是长一点。
class Solution {
public:
int minAddToMakeValid(string S) {
stack<char> s;
int res = 0;
for (auto c : S) {
if (c == '(') {
s.push('(');
} else {
if (!s.empty()) {
s.pop();
} else {
res ++;
}
}
}
return res + s.size();
}
};
日期
2018 年 10 月 14 日 —— 周赛做出来3个题,开心
2018 年 12 月 2 日 —— 又到了周日
【LeetCode】921. Minimum Add to Make Parentheses Valid 解题报告(Python & C++)的更多相关文章
- [LeetCode] 921. Minimum Add to Make Parentheses Valid 使括号有效的最少添加
Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', ...
- 【leetcode】921. Minimum Add to Make Parentheses Valid
题目如下: 解题思路:上周都在忙着参加CTF,没时间做题,今天来更新一下博客吧.括号问题在leetcode中出现了很多,本题的解题思路和以前的括号问题一样,使用栈.遍历Input,如果是'('直接入栈 ...
- 921. Minimum Add to Make Parentheses Valid
Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', ...
- LeetCode 921. 使括号有效的最少添加(Minimum Add to Make Parentheses Valid) 48
921. 使括号有效的最少添加 921. Minimum Add to Make Parentheses Valid 题目描述 给定一个由 '(' 和 ')' 括号组成的字符串 S,我们需要添加最少的 ...
- 【LeetCode】623. Add One Row to Tree 解题报告(Python)
[LeetCode]623. Add One Row to Tree 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problem ...
- [Swift]LeetCode921.使括号有效的最少添加 | Minimum Add to Make Parentheses Valid
Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', ...
- 【LeetCode】989. Add to Array-Form of Integer 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 数组转整数再转数组 模拟加法 日期 题目地址:htt ...
- 【LeetCode】616. Add Bold Tag in String 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 遍历 日期 题目地址:https://leetcode ...
- 【LeetCode】450. Delete Node in a BST 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 日期 题目地址:https://leetcode ...
随机推荐
- 34. Swap Nodes in Pairs
Swap Nodes in Pairs My Submissions QuestionEditorial Solution Total Accepted: 95230 Total Submission ...
- Oracle-SQL语句的语法顺序和执行顺序
SQL语句的语法顺序和执行顺序了,我们常见的SQL语法顺序如下: SELECT DISTINCT <Top Num> <select list>FROM [left_table ...
- Python文件复制shutil模块
Python中shutil模块主要用于文件操作,如复制,属性判断等 1.copyfileobj,拷贝文件内容,将文件句柄赋给该方法 def copyfileobj(src, dst, length=1 ...
- php导出pdf,dompdf中文字体乱码解决办法(特别是代码迁移引起的乱码)
dompdf\lib\fonts\dompdf_font_family_cache.php记住这个文件里面存放的是字体生成的缓存,迁移时如果覆盖了这个文件会导致乱码而且很难找到出错的地方,相信我... ...
- GIFS服务的使用
1.安装Samba服务 登录192.168.200.20虚拟机,首先修改主机名,命令如下: [root@nfs-client ~]# hostnamectl set-hostname samba [r ...
- javaSE中级篇3——集合体系(另外一种存储容器)——更新完毕
集合还是一种工具,所以它们的包都在java.util包下 1.集合的整个体系结构(是需要掌握的体系,完全体系不是这样) 对图中所说的 序和重复 这两词的说明: 序:指的是添加进去的元素和取出来的元素 ...
- LeetCode一维数组的动态和
一维数组的动态和 题目描述 给你一个数组 nums.数组「动态和」的计算公式为:runningSum[i] = sum(nums[0]...nums[i]). 请返回 nums 的动态和. 示例 1: ...
- Git提交规范
Commit message 的格式 每次提交,Commit message 都包括三个部分:Header,Body 和 Footer. <type>(<scope>): &l ...
- Ecshop 后台管理员密码忘记了吧~!~!~!
方法1:把下面的代码保存为文件 mima.php <?php define('IN_ECS', true); require(dirname(__FILE__) . '/includes/ini ...
- C语言把数字转换为字符串的函数
博主原文 C语言itoa()函数和atoi()函数详解(整数转字符C实现) C语言提供了几个标准库函数,可以将任意类型(整型.长整型.浮点型等)的数字转换为字符串. 1.int/float to st ...