301. Remove Invalid Parentheses
每次remove一个( 或者 ) 看看整体valid吗 valid的话这个就是最小的remove数量
1 class Solution { 2 public List<String> removeInvalidParentheses(String s) { 3 List<String> res = new ArrayList<>(); 4 Queue<String> queue = new LinkedList<>(); 5 Set<String> visited = new HashSet<>(); 6 queue.offer(s); 7 visited.add(s); 8 boolean found = false; 9 while(!queue.isEmpty()){ 10 int size = queue.size(); 11 for(int i = 0; i < size; i++){ 12 String str = queue.poll(); 13 if(isValid(str)){ 14 found = true; 15 res.add(str); 16 } 17 18 for(int j = 0; j < str.length(); j++){ 19 if(!(str.charAt(j) == '(') && !(str.charAt(j) == ')')) continue; 20 String str1 = str.substring(0, j) + str.substring(j+1, str.length()); 21 if(!visited.contains(str1)){ 22 visited.add(str1); 23 queue.offer(str1); 24 } 25 } 26 27 } 28 if(found) break; 29 size = queue.size(); 30 } 31 return res; 32 } 33 34 public boolean isValid(String str){ 35 int count = 0; 36 for(int i = 0; i < str.length(); i++){ 37 if(str.charAt(i) == '(') count++; 38 if(str.charAt(i) == ')' && count-- == 0) return false; 39 } 40 return count == 0; 41 } 42 }