301. Remove Invalid Parentheses

2023-05-16

Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.

Note: The input string may contain letters other than the parentheses ( and ).

Example 1:


Input: "()())()"
Output: ["()()()", "(())()"]
  

Example 2:


Input: "(a)())()"
Output: ["(a)()()", "(a())()"]
  

Example 3:


Input: ")("
Output: [""]

FB超级高频题,题目含义是去掉输入字符串中的最少数目的不合法括号,使其成为合法字符串。注意字符串中可能有其他字母。

去掉最少的合法字符,且返回有多种可能,很容易想到用bfs或者dfs来做。其中使用bfs来做,主要思路是将字符串依次去掉一个字符,看是否合法,如果已经合法,就在这个长度的level上操作,不在进行下一层括号去除。代码如何:


class Solution(object):
    def removeInvalidParentheses(self, s):
        """
        :type s: str
        :rtype: List[str]
        """
        if s == "":
            return [""]
        res = []
        self.remove(s, res)
        return res   
    
    
    def isParenthese(self, c):
        if c == '(' or c == ')':
            return True
        else:
            return False 
    
    def isValid(self, s):
        cnt = 0
        for c in s:
            if c == ')':
                cnt -= 1
                if cnt < 0:
                    return False
            elif c == '(':
                cnt += 1
        return cnt == 0
    
    def remove(self, s, res):
        queue = collections.deque()
        queue.append(s)
        used = set()
        curlevel = False
        while queue:
            cur = queue.popleft()
            if self.isValid(cur):
                res.append(cur)
          #important curlevel
= True if curlevel: #important, no process next level continue for i in xrange(len(cur)): if self.isParenthese(cur[i]): sub = cur[:i] + cur[i+1:] if sub not in used: queue.append(sub) used.add(sub) return

可以看到这种写法,在bfs的每层尝试去掉一个单边括号,判断是否合法,如果合法则加入字符串到结果中。同时为了避免重复,在每一层之前已经对某字符串进行处理,后面就需要避免对该字符串进行重复处理,同时也避免了最后重复结果的出现。

这种解法的复杂度分析:最坏是需要处理该字符串的每一层,直到最后,按每层来进行下计算:

1. n*C(n, n)

2.(n-1)*C(n,n-1)

3.(n-2)C(n, n-1)C(n-1, n-2)= (n-2)*C(n, n-2)

依次类推,所以最后的复杂度为:

n*C(n, n) + (n-1)*C(n,n-1) + (n-2)*C(n, n-2)+....+1*C(n,1) = n*(C(n-1,n-1)+C(n-1, n-2)+....C(n-1,1)) = n *2^(n-1)

 这题还有一种dfs的最优解法:详见:https://leetcode.com/problems/remove-invalid-parentheses/discuss/75027/Easy-Short-Concise-and-Fast-Java-DFS-3-ms-solution 复杂度需要分析。

另常考版是返回第一个valid的:详见:https://github.com/tongzhang1994/Facebook-Interview-Coding/blob/master/301.%20Remove%20Invalid%20Parentheses.java

具体思路是正方向扫一次,反方向再扫一次 python代码如下:


class Solution(object):
    def removeInvalidParentheses(self, s):
        """
        only need to return one situation
        :type s: str
        :rtype: str
        """
        if s == "":
            return s
        s = self.removeParentheses(s, ['(', ')'])
        s = self.removeParentheses(s[::-1], [')', '('])[::-1]
        return s

    def removeParentheses(self, s, pair):
        cnt = 0
        new_s = []
        for c in s:
            if c == pair[0]:
                cnt += 1
                new_s.append(c)
            elif c == pair[1]:
                cnt -= 1
                if cnt >= 0:
                    new_s.append(c)
                else:
                    cnt = 0
            else:
                new_s.append(c)
            print cnt
        return "".join(new_s)  

 

转载于:https://www.cnblogs.com/sherylwang/p/9688537.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

301. Remove Invalid Parentheses 的相关文章

随机推荐

  • 黑箱方法-神经网络①

    人工神经网络 人工神经网络的概念 人工神经网络 xff08 Artificial Neural Networks xff0c ANN xff09 是对一组输入信号和一组输出信号之间的关系进行建模 xff0c 使用的模型来源于人类大脑对来自感
  • 飞行前的准备工作

    1 飞控固件 Mission Planner 里的版本 xff0c 好像没有offboard和一些参数的设置 Mission Planner中固件下载 3 3 3 3 4 6 Qground Control中的固件QGC中的固件中有offb
  • make menuconfig 无法启动处理方法

    ake menuconfig Unable to find the ncurses libraries required header files 问题 xff1a lzz 64 lzz virtual machine linux 2 6
  • Ubuntu下自动输入sudo密码

    sudo 自动输入密码 echo 34 password 34 sudo S netstat tlnp S参数 The S stdin option causes sudo to read the password from the sta
  • ssh 或 putty 连接linux报错解决方法

    由于当天多次输入错误密码 xff0c ssh和putty就连接不上了 xff0c 纠结了很久解决问题 ssh连接提示错误 xff1a server unexpectedly closed network connection putty 连
  • Postman 安装及使用入门教程

    安装 本文只是基于 Chrome 浏览器的扩展插件来进行的安装 xff0c 并非单独应用程序 首先 xff0c 你要台电脑 xff0c 其次 xff0c 安装有 Chrome 浏览器 xff0c 那你接着往下看吧 1 官网安装 xff08
  • k8s通过service访问pod(五)--技术流ken

    service 每个 Pod 都有自己的 IP 地址 当 controller 用新 Pod 替代发生故障的 Pod 时 xff0c 新 Pod 会分配到新的 IP 地址 这样就产生了一个问题 xff1a 如果一组 Pod 对外提供服务 x
  • 计算机图形学在GIS中的应用,GIS在交通中的应用与发展-

    xff27 xff29 xff33 在交通中的应用与发展 摘 要 xff1a 地理信息技术的日臻成熟为 xff27 xff29 xff33 在交通领域内的广泛应用创造了一定基础 本文总结了 xff27 xff29 xff33 技术的特点 x
  • 查询MYSQl数据表中的最后一条记录

    mysql select from table order by id DESC limit 1 oracle select from emp where id in select max id from emp 实例 xff1a mysq
  • Windows 10 替换 cmd 的命令行工具

    最近找 Windows 10 的命令行工具 xff0c 发现了 Windows 自带的 PowerShell xff0c 确实功能强大 推荐 查找方法 xff1a 搜索 xff0c PowserShell 打开就能用 https www z
  • 压控恒流源电路

    http bbs 21ic com forum php mod 61 viewthread amp tid 61 1634988 amp highlight 61 4 20ma 最简单简陋的电流输出电路 xff0c 是用 三级管 43 放大
  • OFFBOARD

    Pixhawk的offboard模式 xff0c 是指我们不用遥控器操控飞机 xff0c 也不用地面站给它设定plan 直接用飞机上的板载计算机来与Pixhawk进行通信 xff0c 控制飞机运动 准备工作 xff1a 首先要有一个板载计算
  • 思考: 从曲线中提取出近似直线的一段

    这个问题也是别人问我的 我思考了一些时间 希望抛砖引玉 得到更好的方法 问题是这样的 有一些离散的点 在坐标系中把它们拟合成一条曲线 其中有一段看上去很像是直线 现在要求出这段 34 直线 34 的起始坐标和结束坐标 并把这条线的方程求出来
  • 课程第一天内容《基础交换 一 》

    2019独角兽企业重金招聘Python工程师标准 gt gt gt 项目流程介绍 xff1a 前期 中期 后期 xff1b 项目任务分解 xff1a 工具 甘特图 xff1b 任务 时间 负责人 xff1b 网络设备介绍 xff1a 交换机
  • hewlett-packard 设置 HP启动设置

    开机按 F8进入高级选项安全模式 F9进入启动顺序选择项 F10进入双系统选择项 ESC进入启动选项键选择界面 Delete键进入BIOS please select boot device 请选择启动装置 UEFI boot source
  • 收藏了很久的:5款电影网站!高清大片任意看!就没有找不到资源!

    一放假就剧荒 xff1f 没有时间去电影院看 xff1f 那这5款电影网站你很需要 xff01 Top1 xff1a 中国高清网 各种大片任意看 xff01 最新上映还是好莱坞大片 xff0c 想看什么就看什么 xff01 还怕剧荒 xff
  • 如何查看MySQL数据库的版本

    如何查看MySQL数据库的版本 一 总结 一句话总结 xff1a SQL语句 xff1a select version 命令行 xff1a mysql V 或 mysql version 二 三种方法查看MySQL数据库的版本 转自或参考
  • mysql数据库,变长字符串、定长字符串区别

    变长字符串 varchar varchar 255 所占资源空间是你存储内容的长度 定长字符串 char char 8 不管你存储内容的长度是多少 xff0c 它所占空间就是8 xff0c 如果存储内容长度大于8 xff0c 则会被截取 所
  • How do I install Active Directory on my Windows Server 2003 server?

    How do I install Active Directory on my Windows Server 2003 server by Daniel Petri January 8 2009 Printer Friendly Versi
  • 301. Remove Invalid Parentheses

    Remove the minimum number of invalid parentheses in order to make the input string valid Return all possible results Not