Remove Invalid Parentheses--Nice
2015-11-19 14:32
162 查看
参考链接
题目描述
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 List<String> removeInvalidParentheses(String s){ List<String> ret = new ArrayList<>(); if(s == null) return ret; if(s.length() == 0){ ret.add(s); return ret; } HashSet<String> visited = new HashSet<>(); ArrayDeque<String> queue = new ArrayDeque<>(); queue.add(s); visited.add(s); //找到了最小的就不同接下去了 boolean founded = false; while(!queue.isEmpty()){ String temp = queue.poll(); if(isValid(temp)){ ret.add(temp); founded = true; } //返回最小次数 if(founded) continue; //遍历所有状态 for(int i = 0; i < temp.length(); i++){ if(temp.charAt(i) != ')' && temp.charAt(i) != '(') continue; String splitStr = temp.substring(0, i) + temp.substring(i+1); if(!visited.contains(splitStr)){ visited.add(splitStr); queue.add(splitStr); } } } return ret; } /** * 判断字符串的格式是否有效 * 方法非常巧妙 * 通过count来记录 */ public boolean isValid(String s){ int count = 0; for(int i = 0; i < s.length(); i++){ if('(' == s.charAt(i)) count++; if(')' == s.charAt(i) && count-- == 0) return false; } return count == 0; } }
相关文章推荐
- 用eclipse导入design需要注意的细节
- JS实现——Base64编码解码,带16进制显示
- java入门 第三季4
- 用rm递归删除子目录下所有.o后缀文件
- 磁盘同步rsync+sersync
- Xcode7 免证书真机调试
- MYSQL中limit的使用
- java入门 第三季3
- 。鸟哥私房菜
- AFNetWork 简单实用demo
- CentOS yum安装redis(转)
- java中的路径
- php四种基础算法:冒泡,选择,插入和快速排序法
- 你爱我吗?如何利用BRAT进行中文情感分析语料标注掌握玩家心声
- 较好的类名命名规则
- hive使用技巧(二)——共享中间结果集
- 树、森林及二叉树的相互转换 – 数据结构和算法50
- Java如何判断socket是否已经断开
- 指针遇到的问题,请指教
- Centos下彻底删除oracle