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)
相关推荐
MoRanzhi120317 分钟前
亲和传播聚类算法应用(Affinity Propagation)
人工智能·python·机器学习·数学建模·scikit-learn·聚类
金融OG18 分钟前
99.23 金融难点通俗解释:小卖部经营比喻PPI(生产者物价指数)vsCPI(消费者物价指数)
人工智能·python·机器学习·数学建模·金融·数据可视化
tt55555555555524 分钟前
每日一题-判断是不是完全二叉树
数据结构·算法
是Dream呀1 小时前
Python从0到100(八十六):神经网络-ShuffleNet通道混合轻量级网络的深入介绍
网络·python·神经网络
zxfeng~1 小时前
深度学习之“线性代数”
人工智能·python·深度学习·线性代数
君义_noip1 小时前
信息学奥赛一本通 1607:【 例 2】任务安排 2 | 洛谷 P10979 任务安排 2
算法·动态规划·信息学奥赛·斜率优化
叫我DPT2 小时前
Python 中 `finally` 的执行时机与 `return` 的微妙关系
python
因兹菜2 小时前
[LeetCode]day4 977.有序数组的平方
数据结构·算法·leetcode
weixin_537590452 小时前
《C程序设计》第六章练习答案
c语言·c++·算法
码农小苏242 小时前
K个不同子数组的数目--滑动窗口--字节--亚马逊
java·数据结构·算法