[Leetcode] 301. Remove Invalid Parentheses

本文详细解析了LeetCode上移除无效括号问题的算法解决方案,通过深度优先搜索(DFS)策略,计算并移除多余的左括号和右括号,确保字符串的有效性。文章提供了完整的Java代码实现,并附有YouTube视频教程链接,帮助读者深入理解算法思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problems: https://leetcode.com/problems/remove-invalid-parentheses/

Solution:

class Solution {
    public List<String> removeInvalidParentheses(String s) {
        char[] arr = s.toCharArray();
        int left = 0, right = 0;
        
        // calculate '(' and ')' needed to be deleted
        for(char c : arr) {
            if(c == '(') {
                left++;
            }
            if(c == ')') {
                if(left != 0) {
                    left--;
                } else {
                    right++;
                }
            }
        }
        ArrayList<String> ans = new ArrayList<>();
        dfs(s, 0, left, right, ans);
        return ans;
    }
    
    public boolean isValid(String str) {
        char[] c = str.toCharArray();
        int count = 0;
        for(char ch : c) {
            if(ch == '(') {
                count++;
            } else if (ch == ')') {
                count--;
            }
            if (count < 0) {
                return false; // right appears before left
            }
        }
        return count == 0;
    }
    
    public void dfs(String s, int start, int l, int r, ArrayList<String> ans) {
        // if valid, add to ans
        if (isValid(s)) {
            ans.add(s);
            return;
        }
        
        for (int i = start; i < s.length(); i++) {
        	// only consider the first paranthes if repeated
            if(i != start && s.charAt(i) == s.charAt(i-1)) {
                continue;
            }
            
            if(s.charAt(i) == '(' || s.charAt(i) == ')') {
                String copy = s.substring(0,i) + s.substring(i+1, s.length());
                if(r > 0 && s.charAt(i) == ')') {
                    dfs(copy, i, l, r-1, ans);
                }
                if(l > 0 && s.charAt(i) == '(') {
                    dfs(copy, i, l-1, r, ans);
                }
            }
        }
    }   
}

参考: https://www.youtube.com/watch?v=2k_rS_u6EBk

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值