301. Remove Invalid Parentheses
来源:互联网 发布:阿里云香港服务器能放 编辑:程序博客网 时间:2024/05/29 10:53
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())()"]")(" -> [""]
public class Solution { public static boolean validP(String s){if(s == null || s.length() == 0){return true;}if(s.startsWith(")")){return false;}int count = 0;for(int i=0; i<s.length(); i++){if(s.charAt(i) == '('){count++;}if(s.charAt(i) == ')'){if(count == 0){return false;}count--;}}return count == 0;}public List<String> removeInvalidParentheses(String s) {List<String> result = new ArrayList<String>();Queue<String> queue = new LinkedList<String>();HashSet<String> map = new HashSet<String>();queue.offer(s);map.add(s);boolean found = false;while(!queue.isEmpty()){ int left = 0; int right = 0;s = queue.peek();queue.poll();if(validP(s)){result.add(s);found = true;}if(found){continue;}for(int i=0; i<s.length(); i++){ if(s.charAt(i) == '('){ left++; } if(s.charAt(i) == ')'){ right++; }}for(int i=0; i<s.length(); i++){ char current =s.charAt(i);if((current =='(' && left >= right) || (current==')' && right > left)){String n = s.substring(0, i) + s.substring(i + 1, s.length());if(!map.contains(n)){//剪枝:算好左右括号的数量,不用减少的那一个。queue.offer(n);map.add(n);}}}}return result; }}
0 0
- 301. Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- Leetcode 301. Remove Invalid Parentheses
- leetcode 301. Remove Invalid Parentheses
- [leetcode] 301. Remove Invalid Parentheses
- leetcode.301. Remove Invalid Parentheses
- [LeetCode]--301. Remove Invalid Parentheses
- Leetcode 301. Remove Invalid Parentheses
- 【LeetCode】301. Remove Invalid Parentheses
- [LeetCode]301. Remove Invalid Parentheses
- Leetcode 301. Remove Invalid Parentheses
- 第十七章 JAVA多线程学习
- 第十八章 JAVA多线程交互
- 哈希表和红黑树的对比
- DOMPDF的utf-8字符换行问题
- 初识Mina框架
- 301. Remove Invalid Parentheses
- 在Ubuntu 12.04 LTS 64bit初始化Android编译环境后,遇到重启后卡住在Ubuntu logo,进不了desktop
- Go语言学习之net包(The way to go)
- Flask 快速入门
- U3D的碰撞(Collision)和触发(Trigger)
- LeetCode 300.Longest Increasing Subsequence 在一维数组中找最长序列(好题)
- IOS开发中的window,controller,view
- 278. First Bad Version
- JSon实体类快速生成插件 GsonFormat 1.2.2