【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 ...
随机推荐
- 如何利用官方SDK文件来辅助开发
如何利用官方SDK文件来辅助开发 1.首先要先知道什么是SDK? SDK或者SDK包指的是,半导体厂商针对自己研发的芯片,同步推出的一个软件开发工具包. 它可以简单的为某个程序设计语言提供应用程序接口 ...
- .NET SAAS 架构与设计 -SqlSugar ORM
1.数据库设计 常用的Saas分库分为2种类型的库 1.1 基础信息库 主要存组织架构 .权限.字典.用户等 公共信息 性能优化:因为基础信息库是共享的,所以我们可以使用 读写分离,或者二级缓存来进行 ...
- 从分布式锁角度理解Java的synchronized关键字
分布式锁 分布式锁就以zookeeper为例,zookeeper是一个分布式系统的协调器,我们将其理解为一个文件系统,可以在zookeeper服务器中创建或删除文件夹或文件.设D为一个数据系统,不具备 ...
- 外网无法访问hdfs文件系统
由于本地测试和服务器不在一个局域网,安装的hadoop配置文件是以内网ip作为机器间通信的ip. 在这种情况下,我们能够访问到namenode机器, namenode会给我们数据所在机器的ip地址供我 ...
- 字节面试问我如何高效设计一个LRU,当场懵
首发公众号:bigsai 转载请放置作者和原文(本文)链接 前言 大家好,我是bigsai,好久不见,甚是想念! 最近有个小伙伴跟我诉苦,说他没面到LRU,他说他很久前知道有被问过LRU的但是心想自己 ...
- Maven 学习第一步[转载]
转载至:http://www.cnblogs.com/haippy/archive/2012/07/04/2576453.html 什么是 Maven?(摘自百度百科) Maven是Apache的一个 ...
- 【AWS】【TroubleShooting】EC2实例无法使用SSH远程登陆(EC2 failure for SSH connection)
1. Login AWS web console and check the EC2 instance.
- CentOS 初体验三: Yum 安装、卸载软件
一:Yum 简介 Yum(全称为 Yellow dog Updater, Modified)是一个在Fedora和RedHat以及CentOS中的Shell前端软件包管理器.基于RPM包管理,能够从指 ...
- entfrm开发平台,一个免费开源可视化的无代码开发平台
简介 entfrm开发平台,是一个以模块化为核心的无代码开发平台,是一个集PC和APP快速开发.系统管理.运维监控.开发工具.OAuth2授权.可视化数据源管理与数据构建.API动态生成与统计.工作流 ...
- 2.VUEJS-安装
Vue.js 安装 1.独立版本 我们可以在 Vue.js 的官网上直接下载 vue.min.js 并用 <script> 标签引入. 2.使用 CDN 方法 以下推荐国外比较稳定的两个 ...