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: [""]
publicclassSolution {publicList<String> removeInvalidParentheses(String s) {List<String> res =newArrayList<>();if (s ==null)return res;Set<String> visited =newHashSet<>();Queue<String> queue =newLinkedList<>();// initializequeue.add(s);visited.add(s);boolean found =false;while (!queue.isEmpty()) { s =queue.poll();if (isValid(s)) {// found an answer, add to the resultres.add(s); found =true; }if (found)continue;// generate all possible statesfor (int i =0; i <s.length(); i++) {// we only try to remove left or right parenif (s.charAt(i) !='('&&s.charAt(i) !=')')continue;String t =s.substring(0, i) +s.substring(i +1);if (!visited.contains(t)) {// for each state, if it's not visited, add it to the queuequeue.add(t);visited.add(t); } } }return res; }// helper function checks if string s contains valid paranthesesbooleanisValid(String s) {int count =0;for (int i =0; i <s.length(); i++) {char c =s.charAt(i);if (c =='(') count++;if (c ==')'&& count--==0)returnfalse; }return count ==0; }}