Remove Invalid Parentheses

来源:互联网 发布:bu大都会学院知乎 编辑:程序博客网 时间:2024/05/22 15:24
//BFSpublic class Solution { public List removeInvalidParentheses(String s) { Queue queue = new LinkedList(); HashSet set = new HashSet(); queue.offer(s); List result = new ArrayList(); boolean if_found = false; while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { String str = queue.poll(); if (is_Valid(str)) { if_found = true; result.add(str); continue; } else if (!if_found) { for (int j = 0; j < str.length(); j++) { if (str.charAt(j) == ')' || str.charAt(j) == '(') { StringBuffer sb = new StringBuffer(str); String tmp = String.valueOf(sb.replace(j, j + 1, "")); if (!set.contains(tmp)) queue.offer(tmp); set.add(tmp); } } } } } return result; } public boolean is_Valid(String s) { Stack stack = new Stack(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { stack.push('('); } else if (s.charAt(i) == ')') { if (stack.isEmpty()) { return false; } stack.pop(); } } return stack.isEmpty(); }}//DFSpublic class Solution { List result = new ArrayList(); HashSet visited = new HashSet(); int min_length = 0; public List removeInvalidParentheses(String s) { dfs(s); List r = new ArrayList(); for (String ss : result) { if (ss.length() == min_length) { r.add(ss); } } return r; } public void dfs(String s) { if (is_Valid(s)) { if (s.length() >= min_length) { result.add(s); min_length = s.length(); } } else { for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(' || s.charAt(i) == ')') { String tmp = String.valueOf(new StringBuffer(s).replace(i, i + 1, "")); if (!visited.contains(tmp)) { visited.add(tmp); dfs(tmp); } } } } } public boolean is_Valid(String s) { Stack stack = new Stack(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { stack.push('('); } else if (s.charAt(i) == ')') { if (stack.isEmpty()) { return false; } stack.pop(); } } return stack.isEmpty(); }}
0 0
原创粉丝点击