Remove Invalid Parenthesis


Question

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 ).

Solution

自己是用 DFS 做的,但寫的也是醜,效率不好。參考一下這個神人解法:

    public List<String> removeInvalidParentheses(String s) {
        List<String> ans = new ArrayList<String>();
        remove(s, ans, 0, 0, new char[]{'(', ')'});
        return ans;
    }

    public void remove(String s, List<String> ans, int last_i, int last_j, char[] par) {
        for (int stack = 0, i = last_i; i < s.length(); ++i) {
            if (s.charAt(i) == par[0]) {
                stack++;
            }

            if (s.charAt(i) == par[1]) {
                stack--;
            }

            if (stack >= 0) {
                continue;
            }

            for (int j = last_j; j <= i; ++j) {
                if (s.charAt(j) == par[1] && (j == last_j || s.charAt(j - 1) != par[1])) { // restrict to remove the first ')'
                    remove(s.substring(0, j) + s.substring(j + 1, s.length()), ans, i, j, par);
                } 
            }
            return;
        }

        String reversed = new StringBuilder(s).reverse().toString();
        if (par[0] == '(') {
            remove(reversed, ans, 0, 0, new char[]{')', '('});
        } else {
            ans.add(reversed);
        }
    }

results matching ""

    No results matching ""