301. Remove Invalid Parentheses
作者:互联网
Just use BFS to solve this problem:
1. put the s to queue
2. if s is not a valid string, then remove a '(' or ')', and then put to the queue.
3. once find valid strings, return.
class Solution { public List<String> removeInvalidParentheses(String s) { Set<String> res = new HashSet<>(); Queue<String> queue = new LinkedList<>(); queue.offer(s); Set<String> visited = new HashSet<>(); visited.add(s); while(!queue.isEmpty()){ int size = queue.size(); for(int i=0;i<size;i++){ String str = queue.poll(); if(isValid(str)){ res.add(str); } else{ for(int j=0;j<str.length();j++){ String temp = str.substring(0, j)+str.substring(j+1); if(!visited.contains(temp)){ visited.add(temp); queue.offer(temp); } } } } if(res.size()>0) return new ArrayList(res); } return new ArrayList(res); } private boolean isValid(String s){ int count = 0; for(int i=0;i<s.length();i++){ if(s.charAt(i)=='(') count++; else if(s.charAt(i)==')'){ if(count>0) count--; else return false; } } return count==0; } }
标签:count,Parentheses,return,int,301,Invalid,queue,res,new 来源: https://www.cnblogs.com/feiflytech/p/16110585.html