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: [""]
class Solution {
public List<String> removeInvalidParentheses(String s) {
Set<String> visited = new HashSet<>();
List<String> res = new ArrayList<>();
List<String> current = new ArrayList<>();
List<String> next;
boolean reached = false;
current.add(s);
while(!current.isEmpty()){
next = new ArrayList<>();
for(String prv : current){
visited.add(prv);
//if valid
if(isValid(prv)){
reached = true;
res.add(prv);
}
//not valid
if(!reached){
for(int i=0; i<prv.length(); i++){
char tmp = prv.charAt(i);
if(tmp == '(' || tmp == ')'){
String newString = prv.substring(0,i)+ prv.substring(i+1);
if(!visited.contains(newString)){
next.add(newString);
visited.add(newString);
}
}
}
}
}
if(reached){
break;
}
current = next;
}
return res;
}
private boolean isValid(String s){
Stack<Character> stack = new Stack<>();
for(int i=0; i<s.length(); i++){
char c = s.charAt(i);
if(c == '('){
stack.push(c);
}
else if (c == ')'){
if(stack.isEmpty()){
return false;
}
else{
stack.pop();
}
}
}
return stack.isEmpty();
}
}
看到parenthese的问题,第一反应是用栈。这题要求minimum number,所以想到用BFS遍历解空间树。
思路为:
层次依次为删除0个元素,1个元素,2个元素。。。
层次遍历所有的可能。如果有一种可能是valid,那么不再遍历下面的层。