class Solution {
public List<String> removeInvalidParentheses(String s) {
int left = 0;
int right = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == '('){
left++;
}
else if(s.charAt(i) ==')'){
if(left>0){
left--;
}else{
right++;
}
}
}
List<String> res = new ArrayList<>();
dfs(left, right, res, new StringBuffer(s), 0);
return res;
}
private void dfs(int left, int right, List<String> res, StringBuffer str,int start){
if(left == 0 && right == 0 && validSimple(str)){
res.add(str.toString());
return;
}
for(int i = start; i < str.length(); i++){
if(i != start && str.charAt(i) == str.charAt(i-1)) continue;
StringBuffer temp = new StringBuffer(str);
if(left != 0 && str.charAt(i) == '('){
str.delete(i,i+1);
left--;
dfs(left,right,res, str, i);
left++;
str = temp;
}else if(right != 0 && str.charAt(i) == ')'){
str.delete(i,i+1);
right--;
dfs(left,right,res, str, i);
right++;
str = temp;
}
}
}
private boolean valid(StringBuffer s){
if(s == null || s.length() == 0) return true;
Stack<Character> stk = new Stack<Character>();
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == '('){
stk.push(s.charAt(i));
}
else if(s.charAt(i) == ')'){
if(stk.isEmpty()) return false;
stk.pop();
}
}
return stk.isEmpty();
}
private boolean validSimple(StringBuffer s){
int count = 0;
for(int i = 0 ; i < s.length(); i++){
if(s.charAt(i) == '(') count++;
if(s.charAt(i) == ')') {
if(count <= 0) return false;
count--;
}
}
return count == 0;
}
}
[leetcode]301. Remove Invalid Parentheses
最新推荐文章于 2023-10-30 07:17:13 发布