【LeetCode】301. Remove Invalid Parentheses 删除无效的括号(Hard)(JAVA)

【LeetCode】301. Remove Invalid Parentheses 删除无效的括号(Hard)(JAVA)

题目地址: https://leetcode.com/problems/remove-invalid-parentheses/

题目描述:

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: [""]

题目大意

删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。

说明: 输入可能包含了除 ( 和 ) 以外的字符。

解题方法

  1. 要判断一个字符串是否有无效的括号,可以先从左到右遍历左括号数始终大于等于右括号数,从右到左遍历右括号数始终大于等于左括号数
  2. 如果左到右遍历,中途遇到左括号数始终小于右括号数,说明这之前肯定需要删除一个左括号,那就删除这之前的一个左括号,然后把结果继续递归找出结果
  3. 从右往左遍历也是同样处理
  4. note: 如果遇到字符串有效,直接就返回当前字符串
class Solution {
    public List<String> removeInvalidParentheses(String s) {
        Set<String> set = new HashSet<>();
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                count++;
            } else if (s.charAt(i) == ')') {
                count--;
            }
            if (count >= 0) continue;
            for (int j = 0; j <= i; j++) {
                if (s.charAt(j) != ')') continue;
                if (j != 0 && s.charAt(j - 1) == ')') continue;
                List<String> next = removeInvalidParentheses(s.substring(0, j) + s.substring(j + 1));
                set.addAll(next);
            }
            return new ArrayList<>(set);
        }
        if (count == 0) {
            set.add(s);
            return new ArrayList<>(set);
        }
        count = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) == ')') {
                count++;
            } else if (s.charAt(i) == '(') {
                count--;
            }
            if (count >= 0) continue;
            for (int j = s.length() - 1; j >= i; j--) {
                if (s.charAt(j) != '(') continue;
                if (j != s.length() - 1 && s.charAt(j + 1) == '(') continue;
                List<String> next = removeInvalidParentheses(s.substring(0, j) + s.substring(j + 1));
                set.addAll(next);
            }
            break;
        }
        return new ArrayList<>(set);
    }
}

执行耗时:8 ms,击败了58.29% 的Java用户
内存消耗:39.4 MB,击败了29.81% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值