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: [""]
思路:有一个要点是,要从左往右,也要从右往左。题意就是在表达式里删除最少的活好使之有效。
用count来计算左右括号是否平衡,左加右减。如果平衡了且当前的last_i等于char[]里的右边,就进入循环去判断,然后开始每次去掉第一个遇到的par[1]. last_j 记录最后一个删除的元素。
class Solution {
public List<String> removeInvalidParentheses(String s) {
List<String> ans = new ArrayList<String>();
remove(s, ans, 0, 0, 0, new char[] {'(', ')'});
return ans;
}
private void remove(String s, List<String> ans, int count, int last_i, int last_j, char[] par) {
if (last_i == s.length() && par[0] == ')') {
System.out.println("1+"+s);
ans.add(new StringBuilder(s).reverse().toString());
return;
}
if (last_i == s.length() && par[0] == '(') {
System.out.println("2:"+s);
String reverse = new StringBuilder(s).reverse().toString();
System.out.println("1:"+reverse);
remove(reverse, ans, 0, 0, 0, new char[] {')', '('});
return;
}
char c = s.charAt(last_i);
if(c==par[1] && count ==0){
for(int j= last_j;j<=last_i;j++){
if(s.charAt(j) == par[1] &&(j == last_j ||s.charAt(j-1)!=par[1])){
remove(s.substring(0,j) + s.substring(j+1), ans,0,last_i, j, par);
}
}
}else{
if(c == par[0])count++;
if(c == par[1])count--;
remove(s, ans, count, last_i + 1, last_j, par);
}
}
}