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

时间:2023-02-18 19:05:33

作者: 负雪明烛
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 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.

题目大意

求最少添加几个括号才能使得整个表达式是合法的括号表达式。

解题方法

遇到括号匹配题一般想到用栈。这题也不例外。

同样是对字符串进行一次遍历,如果遍历到的位置是左括号,那么要进行判断:

  1. 如果栈顶是右括号,那么说明判断前面字符串缺少了几个括号
  2. 否则,需要直接进栈

如果遍历到的位置是右括号,那么直接进栈。

我花了半个小时才把这个题做出来啊,错误的地方就在于左括号的判断上。第一,判断前面缺少几个括号的时候,我把栈所有的元素全部退栈了,这样就错误了,因为可能前面部分匹配,再往前的左括号需要等待后面的右括号来了之后才能判断。所以,这个问题的解决方法是如果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++)的更多相关文章

  1. &lbrack;LeetCode&rsqb; 921&period; Minimum Add to Make Parentheses Valid 使括号有效的最少添加

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

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

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

  3. 921&period; Minimum Add to Make Parentheses Valid

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

  4. LeetCode 921&period; 使括号有效的最少添加&lpar;Minimum Add to Make Parentheses Valid&rpar; 48

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

  5. 【LeetCode】623&period; Add One Row to Tree 解题报告(Python)

    [LeetCode]623. Add One Row to Tree 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problem ...

  6. &lbrack;Swift&rsqb;LeetCode921&period;使括号有效的最少添加 &vert; Minimum Add to Make Parentheses Valid

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

  7. 【LeetCode】989&period; Add to Array-Form of Integer 解题报告(C&plus;&plus;)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 数组转整数再转数组 模拟加法 日期 题目地址:htt ...

  8. 【LeetCode】616&period; Add Bold Tag in String 解题报告&lpar;C&plus;&plus;&rpar;

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

  9. 【LeetCode】450&period; Delete Node in a BST 解题报告 &lpar;Python&C&plus;&plus;&rpar;

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

随机推荐

  1. EasyUI管理后台模板(附源码)

    下载地址:http://files.cnblogs.com/wyguo/easyui_demo.zip

  2. 每天一个 Linux 命令(17):whereis 命令

    whereis命令只能用于程序名的搜索,而且只搜索二进制文件(参数-b).man说明文件(参数-m)和源代码文件(参数-s).如果省略参数,则返回所有信息. 和find相比,whereis查找的速度非 ...

  3. &lpar;转&rpar;苹果消息推送服务器 php 证书生成

    1.准备好 aps_developer_identity.cer , push.p12这两个证书文件 2. 生成证书如下: openssl x509 -in aps_developer_identit ...

  4. find系列之xargs命令

    xargs的功能-->     将标准输入转换为命令行参数,供后面的命令调用,但是一次只能依据-d和-n限定的行数来推送一行 xargs的作用-->     使那些不能利用stdin的命令 ...

  5. zookeeper curator使用caches实现各种监听

    1.篇首语 curator是zookeeper的一个高级api开发包.封装了zookeeper众多的recipes,并且实现了一些新的recipes原语,最重要的是基于zookeeper提供的各种机制 ...

  6. 从零开始搭建springboot&plus;mybatis&plus;thymeleaf增删改查示例

    环境说明: 开发工具:Eclipse Mars.2 Release(4.5.2) JDK:1.8 Maven:3.3.3 注:Eclipse需安装sts插件,安装方法请自行百度 1. 新建maven工 ...

  7. zabbix的自动发现、自定义添加监控项目、配置邮件告警

    1.zabbix的自动发现这里的自动发现,所显示出来的是规则的上自动了现 然后 可以对其内容进行相关的配制,如时间或周期 注意:对于单个主机的规则,可以自行添加或删除, 但对于已经添加好了的规则,若需 ...

  8. django 环境配置&period;

    1. 一个虚拟环境对应一个 dajngo项目 2. mkvirtruenv pycham 创建Pure Python 新项目,不是Django 2018.3 其他版本 3.  Add Configur ...

  9. oracle分区分表

    (1) 表空间及分区表的概念表空间: 是一个或多个数据文件的集合,所有的数据对象都存放在指定的表空间中,但主要存放的是表, 所以称作表空间.分区表:        当表中的数据量不断增大,查询数据的速 ...

  10. phpStudy安装教程

    1.在phpStudy官网下载安装包(http://phpstudy.php.cn/)2.解压安装后,若提示没有“VC9.VC11.VC14运行库,注意是X86 32位”,则在phpStudy下载对应 ...