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 )
.
Examples:
"()())()" -> ["()()()", "(())()"] "(a)())()" -> ["(a)()()", "(a())()"] ")(" -> [""]
Solution:
public class Solution {
public List<String> removeInvalidParentheses(String s) {
//bfs优点笨,因为它生成了所有解,但是很有效
List<String> ans=new ArrayList<String>();
if(s==null) return ans;
Queue<String> q=new LinkedList<String>();
Set<String> visited=new HashSet<String>();
q.add(s);
visited.add(s);
boolean found=false;
while(!q.isEmpty())
{
s=q.poll();
if(isValid(s))
{
ans.add(s);
found=true;
}
if(found) continue; //确保了是永远产生去除括号最少的情况
for(int i=0;i<=s.length()-1;i++)
{
if(s.charAt(i)!='('&&s.charAt(i)!=')')
continue;
String t=s.substring(0,i)+s.substring(i+1);
if(!visited.contains(t))
{
q.add(t);
visited.add(t);
}
}
}
// if(!found)
// {
// ans.add("");
// }
return ans;
}
public boolean isValid(String s)
{
int count=0;
for(int i=0;i<=s.length()-1;i++)
{
if(s.charAt(i)=='(') count++;
if(s.charAt(i)==')'&&count--==0) return false;
}
return count==0;
}
}
这是bfs解法,其实还有dfs解法,如下~
public List<String> removeInvalidParentheses(String s) {
List<String> ans=new ArrayList<String>();
if(s==null) return ans;
remove(s, ans, 0, 0, new char[]{'(', ')'});
if(ans.size()==0) ans.add("");
return ans;
}
public void remove(String s, List<String> ans, int last_i, int last_j, char[] pat){
int stack=0;
for(int i=last_i;i<=s.length()-1;i++)
{
if(s.charAt(i)==pat[0]) stack++;
if(s.charAt(i)==pat[1]) stack--;
if(stack>=0) continue;
for(int j=last_j;j<=i;j++)
{
if(s.charAt(j)==pat[1]&&(j==last_j||s.charAt(j-1)!=pat[1]))//j位置时连续‘)’的第一个
remove(s.substring(0,j)+s.substring(j+1),ans,i,j,pat);
}
return; //return 放在这里?为什么呢
}
String rev=new StringBuilder(s).reverse().toString();
//如果当前字符是未反转的
if(pat[0]=='(')
{
remove(rev,ans,0,0,new char[]{')', '('});
}
else
ans.add(rev);
}