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
最新推荐文章于 2020-08-26 09:55:23 发布
本文介绍了一种通过深度优先搜索(DFS)去除字符串中无效括号的算法,以确保最终字符串中的括号有效且数量最少。算法首先计算需要删除的左括号和右括号的数量,然后使用递归的深度优先搜索遍历所有可能的删除组合,最后验证剩余字符串的有效性。
摘要由CSDN通过智能技术生成