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
- [LeetCode] Remove Invalid Parentheses
- LeetCode -- Remove Invalid Parentheses
- Remove Invalid Parentheses--Nice
- Remove Invalid Parentheses
- leetcode Remove Invalid Parentheses
- Leetcode214: Remove Invalid Parentheses
- LeetCode Remove Invalid Parentheses
- [Leetcode]Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- leetcode:Remove Invalid Parentheses
- leetcode - Remove Invalid Parentheses
- Remove Invalid Parentheses
- 【Leetcode】Remove Invalid Parentheses
- LeetCode:Remove Invalid Parentheses
- Remove Invalid Parentheses
- Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- Remove Invalid Parentheses
- RecyclerView的使用记录
- 几道笔试题
- 统计数字
- [LeetCode265]Paint House II
- display:inline、block、inline-block的区别
- Remove Invalid Parentheses
- [LeetCode266]Palindrome Permutation
- [LeetCode267]Palindrome Permutation II
- 手机原型设计
- MMU段式映射(VA -> PA)过程分析
- sizeof[Q]
- *LeetCode-Flatten 2D Vector
- 浅谈C++中的Const
- 你的人生是在挑水还是在挖井