301. Remove Invalid Parentheses
package LeetCode_301 import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashSet /** * 301. Remove Invalid Parentheses * https://leetcode.com/problems/remove-invalid-parentheses/description/ * * 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: [""] * */ class Solution { /* * solution: BFS, Time complexity:O(2^n), Space complexity:O(2^n) * */ fun removeInvalidParentheses(s: String): List<String> { val result = ArrayList<String>() val visited = HashSet<String>() val queue = LinkedList<String>() queue.offer(s) while (queue.isNotEmpty()) { val cur = queue.poll() if (visited.contains(cur)) { continue } visited.add(cur) if (isValidParenthese(cur)) { result.add(cur) } //if found in this level, no need to loop again if (result.size != 0) { continue } for (i in cur.indices) { if (cur[i] == '(' || cur[i] == ')') { /* check every children * for example:()())(), * children: remove first '('=>)())() * remove the second:')'=>(())() * */ val children = cur.substring(0, i) + cur.substring(i + 1, cur.length) queue.offer(children) } } } //println(result) return result } private fun isValidParenthese(s: String): Boolean { var count = 0 for (c in s) { if (c == '(') { count++ } else if (c == ')') { count-- } if (count < 0) { return false } } return count == 0 } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)