LeetCode – Remove Invalid Parentheses (Java)

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

Examples:
“()())()” -> [“()()()”, “(())()”]
“(a)())()” -> [“(a)()()”, “(a())()”]
“)(” -> [“”]

Java Solution

This problem can be solve by using DFS.

public class Solution {
    ArrayList<String> result = new ArrayList<String>();
    int max=0; 
 
    public List<String> removeInvalidParentheses(String s) {
        if(s==null)
            return result;
 
        dfs(s, "", 0, 0);
        if(result.size()==0){
            result.add("");
        }
 
        return result;
    }
 
    public void dfs(String left, String right, int countLeft, int maxLeft){
        if(left.length()==0){
            if(countLeft==0 && right.length()!=0){
                if(maxLeft > max){
                    max = maxLeft;
                }
 
                if(maxLeft==max && !result.contains(right)){
                    result.add(right);
                }
            }
 
            return;
        }
 
        if(left.charAt(0)=='('){
            dfs(left.substring(1), right+"(", countLeft+1, maxLeft+1);//keep (
            dfs(left.substring(1), right, countLeft, maxLeft);//drop (
        }else if(left.charAt(0)==')'){
            if(countLeft>0){
                dfs(left.substring(1), right+")", countLeft-1, maxLeft);
            }
 
            dfs(left.substring(1), right, countLeft, maxLeft);
 
        }else{
            dfs(left.substring(1), right+String.valueOf(left.charAt(0)), countLeft, maxLeft);
        }
    }
}

2 thoughts on “LeetCode – Remove Invalid Parentheses (Java)”

  1. could we before fixing overall find longest balanced sub=string , and after try to fix
    rest of …???

    on geeks exist BFS solution,. basically remove each symbol, and check balanced or not.

    ++ hash to keep only copy


  2. public static List removeInvalidParentheses(String str) {
    if (str.length() == 0) {
    return null;
    }
    Map brackets = new HashMap();
    brackets.put('(', ')');
    LinkedList stack = new LinkedList();
    List result = new ArrayList();
    for (int i = 0; i 0) {
    if (brackets.containsValue(chars[j])) {
    char temp = chars[j];
    chars[j] = ' ';
    String valid = new String(chars);
    result.add(valid.replaceAll("\s",""));
    chars[j] = temp;
    }
    j--;
    }
    }
    }
    }
    return result;
    }

Leave a Comment