首页 > 代码库 > Remove Invalid Parentheses
Remove Invalid Parentheses
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 (
and )
.
Examples:
"()())()" -> ["()()()", "(())()"] "(a)())()" -> ["(a)()()", "(a())()"] ")(" -> [""]
1 public class Solution { 2 private List<String> res = new ArrayList<String>(); 3 private int max = 0; 4 public List<String> removeInvalidParentheses(String s) { 5 dfs(s, "", 0, 0); 6 if (res.size() == 0) { 7 res.add(""); 8 } 9 10 return res; 11 } 12 13 private void dfs(String str, String subRes, int countLeft, int maxLeft) { 14 if (countLeft > str.length()) return; 15 if (maxLeft + str.length() / 2 < max) return; 16 if (str.length() == 0) { 17 if (countLeft == 0 && subRes.length() != 0) { 18 if (maxLeft > max) { 19 max = maxLeft; 20 } 21 if (max == maxLeft && !res.contains(subRes)) { 22 res.add(subRes.toString()); 23 } 24 } 25 return; 26 } 27 28 if (str.charAt(0) == ‘(‘) { 29 dfs(str.substring(1), subRes.concat("("), countLeft + 1, maxLeft + 1); 30 dfs(str.substring(1), subRes, countLeft, maxLeft); 31 } else if (str.charAt(0) == ‘)‘) { 32 if (countLeft > 0) { 33 dfs(str.substring(1), subRes.concat(")"), countLeft - 1, maxLeft); 34 } 35 dfs(str.substring(1), subRes, countLeft, maxLeft); 36 } else { 37 dfs(str.substring(1), subRes.concat(String.valueOf(str.charAt(0))), countLeft, maxLeft); 38 } 39 } 40 }
Remove Invalid Parentheses
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。