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 with B), where A and B are valid strings, or
  • It can be written as (A), where A 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:

  1. S.length <= 1000
  2. S only consists of '(' and ')' characters.

这道题给了一个括号字符串,可能是非法的,让我们补充最少数量的半括号,使其变为合法的括号字符串。那么实际上只要统计出需要添加的左右括号个数即可,这里使用两个变量 left 和 right,分别表示需要的左右括号个数。遍历字符串S,若遇到左括号,说明此时需要右括号,则 right 自增1;若遇到了右括号,若此时 right 大于0,说明当前的右括号可以用来匹配之前的左括号,不需要另加右括号,所以此时 right 自减1;而若此时 right 为0,说明当前的右括号前面没有左括号可以跟其匹配,则此时 left 自增1,表示需要额外的左括号。最后返回 left+right 即为所求,参见代码如下:


解法一:

class Solution {
public:
int minAddToMakeValid(string S) {
int left = 0, right = 0;
for (char c : S) {
if (c == '(') {
++right;
} else if (right > 0) {
--right;
} else {
++left;
}
}
return left + right;
}
};

我们可以只用一个变量 cnt,表示当前左括号的个数。遍历字符串S,当遇到左括号,而此时 cnt 为负数时,表示此时右括号是多余左括号的,而当前遇到的左括号不能匹配之前的右括号,所以将 cnt 的绝对值加到结果 res 中,表示需要这多么的左括号来匹配之前多出的右括号。然后此时 cnt 自增1,因为当前遇到的是左括号,若当前遇到右括号,则 cnt 自减1,最终返回 res 加上 cnt 的绝对值即为所求,参见代码如下:


解法二:

class Solution {
public:
int minAddToMakeValid(string S) {
int res = 0, cnt = 0;
for (char c : S) {
if (c == '(') {
if (cnt < 0) {
res += abs(cnt);
cnt = 0;
}
++cnt;
} else {
--cnt;
}
}
return res + abs(cnt);
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/921

类似题目:

Remove Invalid Parentheses

Different Ways to Add Parentheses

Longest Valid Parentheses

Generate Parentheses

Valid Parentheses

参考资料:

https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/

https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/181132/C%2B%2BJavaPython-Straight-Forward-One-Pass

https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/181086/Java-two-one-pass-7-liners-space-O(n)-and-O(1)-respectively

[LeetCode All in One 题目讲解汇总(持续更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)

[LeetCode] 921. Minimum Add to Make Parentheses Valid 使括号有效的最少添加的更多相关文章

  1. 【LeetCode】921. Minimum Add to Make Parentheses Valid 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址: https://leetcode. ...

  2. 【leetcode】921. Minimum Add to Make Parentheses Valid

    题目如下: 解题思路:上周都在忙着参加CTF,没时间做题,今天来更新一下博客吧.括号问题在leetcode中出现了很多,本题的解题思路和以前的括号问题一样,使用栈.遍历Input,如果是'('直接入栈 ...

  3. 921. Minimum Add to Make Parentheses Valid

    Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', ...

  4. LeetCode 921. 使括号有效的最少添加(Minimum Add to Make Parentheses Valid) 48

    921. 使括号有效的最少添加 921. Minimum Add to Make Parentheses Valid 题目描述 给定一个由 '(' 和 ')' 括号组成的字符串 S,我们需要添加最少的 ...

  5. [Swift]LeetCode921.使括号有效的最少添加 | Minimum Add to Make Parentheses Valid

    Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', ...

  6. leetcode 921. 使括号有效的最少添加(Python)

    class Solution: def minAddToMakeValid(self, S): """ :type S: str :rtype: int "&q ...

  7. leetcode 921. 使括号有效的最少添加

    问题描述 给定一个由 '(' 和 ')' 括号组成的字符串 S,我们需要添加最少的括号( '(' 或是 ')',可以在任何位置),以使得到的括号字符串有效. 从形式上讲,只有满足下面几点之一,括号字符 ...

  8. [LeedCode]921. 使括号有效的最少添加

    题目描述: 给定一个由 '(' 和 ')' 括号组成的字符串 S,我们需要添加最少的括号( '(' 或是 ')',可以在任何位置),以使得到的括号字符串有效. 从形式上讲,只有满足下面几点之一,括号字 ...

  9. [leetcode-921-Minimum Add to Make Parentheses Valid]

    Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', ...

随机推荐

  1. 在Windows下的virtualenv中搭建Flask+MySQLDb开发环境

    virtualenv和Flask的安装前面已经介绍过了,这里主要讲如何在venv中安装MySQL 安装MySQLdb 下载MySQL-python-1.2.3.win32-py2.7.exe并安装. ...

  2. Spring Boot +Bootstrap 图片上传与下载,以及在bootstrap-table中的显示

    1.前台上传: <input type="file" name="file" id="file"> 2.后台的接收与处理: St ...

  3. WPF 隐藏式控件

    没用Popup用的面板控件,全部代码使用xaml的触发器. 代码: <Grid> <DockPanel> <StackPanel Background=" Do ...

  4. Maven配置教程详解

    Maven的安装与配置 一.在https://www.cnblogs.com/zyx110/p/10799387.html中下载以下maven安装包 解压缩即可 根据你的安装路径配置maven环境变量 ...

  5. ASP.NET Core 3.0 使用AspectCore-Framework实现AOP

    AspectCore是适用于Asp.Net Core 平台的轻量级Aop(Aspect-oriented programming)解决方案,它更好的遵循Asp.Net Core的模块化开发理念,使用A ...

  6. 一款对Postman支持较好的接口文档生成工具

    最近要编写接口文档给测试和前端看,通过网上查阅资料,也认识了很多款接口文档生成工具,比如易文档.ApiPost.ShowDoc.YApi.EoLinker.DOClever.apizza等,通过对这几 ...

  7. asp.net 获取当前,相对,绝对路径

    一.C#获取当前路径的方法: 1. System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName -获取模块的完整路径. 2. ...

  8. 【maven】父子项目的一般姿势

    一.为什么需要创建maven父子项目. 一般一个业务较多的项目,如果我们做服务拆分的话,有些公共的模块就只能做成jar包了.你将util.constant.model封装成jar包是比较好的,如果da ...

  9. Nginx+keepalived(高可用双主模式)

    Nginx+keepalived(高可用双主模式) tips:前面已经介绍了nginx+keepalived高可用主从模式,今天补充下高可用的双主模式,均可以作为主机使用 server1:192.16 ...

  10. 英语cartialgenous鹿茸cartialgenous单词

    鹿茸cartialgenous是雄鹿未骨化密生茸毛的幼角,主要从梅花鹿和马鹿头上采收,前者叫花鹿茸.黄毛茸,后者叫青毛茸.雄鹿到了一定年纪头上就会长角,初发时嫩如春笋,其表面上有一层纤细茸毛的嫩角就是 ...