LeetCode 301: Remove Invalid Parenthesis

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 301: Remove Invalid Parenthesis相关的知识,希望对你有一定的参考价值。

Note:

It could be other chars in the String. Do not count as invalid parenthesis.

class Solution {
    public List<String> removeInvalidParentheses(String s) {
        List<String> result = new ArrayList<>();
        remove(s, result, 0, 0, new char[]{‘(‘, ‘)‘});
        return result;
    }
    
    private void remove(String input, List<String> result, int lastI, int lastJ, char[] pattern) {
        for (int count = 0, i = lastI; i < input.length(); i++) {
            if (input.charAt(i) == pattern[0]) {
                count++;
            }
            if (input.charAt(i) == pattern[1]) {
                count--;
            }
            
            if (count >= 0) {
                continue;
            }
            
            for (int j = lastJ; j <= i; j++) {
                if (input.charAt(j) == pattern[1] && (j == lastJ || input.charAt(j - 1) != pattern[1])) {
                    remove(input.substring(0, j) + input.substring(j + 1), result, i, j, pattern);
                }
            }
            return;
        }
        
        String reversed = new StringBuilder(input).reverse().toString();
        if (pattern[0] == ‘(‘) {
            remove(reversed, result, 0, 0, new char[]{‘)‘, ‘(‘});
        } else {
            result.add(reversed);
        }
    }
}

 

以上是关于LeetCode 301: Remove Invalid Parenthesis的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode题301—Remove Invalid Parentheses

leetcode 301-Remove Invalid Parentheses(hard)

[leetcode]301. Remove Invalid Parentheses 去除无效括号

[LeetCode] 301. Remove Invalid Parentheses 移除非法括号

LeetCode 301. Remove Invalid Parentheses(DP)

leetcode301. Remove Invalid Parentheses