leetcode - 1249. Minimum Remove to Make Valid Parentheses

Description

Given a string s of '(' , ')' and lowercase English characters.

Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.

Formally, a parentheses string is valid if and only if:

复制代码
It is the empty string, contains only lowercase characters, 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.

Example 1:

复制代码
Input: s = "lee(t(c)o)de)"
Output: "lee(t(c)o)de"
Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.

Example 2:

复制代码
Input: s = "a)b(c)d"
Output: "ab(c)d"

Example 3:

复制代码
Input: s = "))(("
Output: ""
Explanation: An empty string is also valid.

Constraints:

复制代码
1 <= s.length <= 10^5
s[i] is either'(' , ')', or lowercase English letter.

Solution

List

Go through the string from left to right, use a left_cnt to keep track of how many ( we have visited, and decrease when there's a ), discard redundant ) during this process.

Go through the string again, this time from right to left, use a right_cnt to keep track of how may ) we have, and decrease when there's a (, discard ( this time.

Time complexity: o ( n ) o(n) o(n)

Space complexity: o ( n ) o(n) o(n)

Stack

Use a stack to store all the (, and pop when there's a ), at the end, all the remaining (s are those we need to discard.

Time complexity: o ( n ) o(n) o(n)

Space complexity: o ( n ) o(n) o(n)

Code

List

python3 复制代码
class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        left_cnt = 0
        res = []
        for i in range(len(s)):
            if s[i] not in ('(', ')'):
                res += s[i]
            elif s[i] == '(':
                res += s[i]
                left_cnt += 1
            elif s[i] == ')' and left_cnt > 0:
                res += s[i]
                left_cnt -= 1
        right_cnt = 0
        new_res = ''
        for i in range(len(res) - 1, -1, -1):
            if res[i] not in ('(', ')'):
                new_res += res[i]
            elif res[i] == ')':
                new_res += res[i]
                right_cnt += 1
            elif res[i] == '(' and right_cnt > 0:
                new_res += res[i]
                right_cnt -= 1
        return new_res[::-1]

Stack

python3 复制代码
class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        stack = []
        discard = []
        for i in range(len(s)):
            if s[i] == '(':
                stack.append(i)
            elif s[i] == ')':
                if stack:
                    stack.pop()
                else:
                    discard.append(i)
        discard += stack
        res = []
        for i in range(len(s)):
            if i not in discard:
                res.append(s[i])
        return ''.join(res)
相关推荐
每天进步一点点dlb20 小时前
JVM中的垃圾回收算法和垃圾回收器
jvm·算法
花开花富贵20 小时前
表白❤不够格,草莓熊来帮忙!
python
我爱鸢尾花20 小时前
CNN基础理论讲解及Python代码复现
人工智能·python·深度学习·神经网络·算法·机器学习·cnn
大数据张老师20 小时前
数据结构——二叉搜索树
数据结构·算法·二叉搜索树·查找·关键路径
love530love20 小时前
【笔记】解决 ComfyUI 安装节点 ComfyUI-Addoor (葵花宝典)后启动报错:No module named ‘ComfyUI-Addoor’
linux·运维·前端·人工智能·windows·笔记·python
love530love20 小时前
【笔记】ComfyUI KeyError: ‘tensorrt‘ 错误的完整解决方案
windows·笔记·python·pycharm
zzywxc78720 小时前
解锁 Rust 开发新可能:从系统内核到 Web 前端的全栈革命
开发语言·前端·python·单片机·嵌入式硬件·rust·scikit-learn
攻城狮CSU20 小时前
类型转换汇总 之C#
java·算法·c#
小老鼠不吃猫21 小时前
C++ STL <algorithm>中泛型算法:查找、排序、修改、统计、生成
c++·算法·排序算法
白杆杆红伞伞21 小时前
01_svm_二分类
算法·支持向量机·分类