[LeetCode]Remove Invalid Parentheses
2017-07-07 16:07
330 查看
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
Examples:
public class Solution {
public List<String> removeInvalidParentheses(String s) {
dfs(0,0,0,s);
if(re.isEmpty()) re.add("");
return new ArrayList<String>(re);
}
HashSet<String> re=new HashSet<String>();
StringBuffer sb=new StringBuffer();
int max=0;
public void dfs(int k,int left,int right,String s){
if(k==s.length()){
if(right==left){
if(left*2==max) re.add(sb.toString());
else if(left*2>max){
max=left*2;
re.clear();
re.add(sb.toString());
}
}
return;
}
char ch=s.charAt(k);
sb.append(s.charAt(k));
if(ch=='('){
dfs(k+1,left+1,right,s);
}else if(ch==')'){
if(left>right) dfs(k+1,left,right+1,s);
}else{
dfs(k+1,left,right,s);
}
sb.deleteCharAt(sb.length()-1);
if(ch=='('||ch==')') dfs(k+1,left,right,s);
}
}
Note: The input string may contain letters other than the parentheses
(and
).
Examples:
"()())()" -> ["()()()", "(())()"] "(a)())()" -> ["(a)()()", "(a())()"] ")(" -> [""]
public class Solution {
public List<String> removeInvalidParentheses(String s) {
dfs(0,0,0,s);
if(re.isEmpty()) re.add("");
return new ArrayList<String>(re);
}
HashSet<String> re=new HashSet<String>();
StringBuffer sb=new StringBuffer();
int max=0;
public void dfs(int k,int left,int right,String s){
if(k==s.length()){
if(right==left){
if(left*2==max) re.add(sb.toString());
else if(left*2>max){
max=left*2;
re.clear();
re.add(sb.toString());
}
}
return;
}
char ch=s.charAt(k);
sb.append(s.charAt(k));
if(ch=='('){
dfs(k+1,left+1,right,s);
}else if(ch==')'){
if(left>right) dfs(k+1,left,right+1,s);
}else{
dfs(k+1,left,right,s);
}
sb.deleteCharAt(sb.length()-1);
if(ch=='('||ch==')') dfs(k+1,left,right,s);
}
}
相关文章推荐
- [LeetCode] Remove Invalid Parentheses
- LeetCode-Remove Invalid Parentheses
- LeetCode "Remove Invalid Parentheses"
- [LeetCode] Remove Invalid Parentheses 移除非法括号
- Remove Invalid Parentheses - LeetCode
- leetcode Remove Invalid Parentheses
- [leetcode] Remove Invalid Parentheses
- Leetcode 301 Remove Invalid Parentheses
- [Leetcode]Remove Invalid Parentheses
- leetcode Remove Invalid Parentheses
- [LeetCode][JavaScript]Remove Invalid Parentheses
- Leetcode214: Remove Invalid Parentheses
- leetcode:Remove Invalid Parentheses
- Leetcode: Remove Invalid Parentheses
- LeetCode Remove Invalid Parentheses
- LeetCode:Remove Invalid Parentheses
- leetcode:bfs: Remove Invalid Parentheses(301)
- [LeetCode] Remove Invalid Parentheses
- 【Leetcode】Remove Invalid Parentheses
- leetcode - Remove Invalid Parentheses