[leetcode] Remove Invalid Parentheses
2015-11-05 22:03
417 查看
题目:
分析:题目的意思是最少去掉无效括号的个数,可能去掉1个括号,也可能去掉2个,3个等等。我们可以借助广度优先搜索(BFS)的思想,如下:
Java代码如下:
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个括号,也可能去掉2个,3个等等。我们可以借助广度优先搜索(BFS)的思想,如下:
"())()" 去掉1个 "))()" "()()" "()()" "()))" "())(" 去掉2个 ")()" ................................. ................
Java代码如下:
public List<String> removeInvalidParentheses(String s) { List<String> result = new ArrayList<String>(); Set<String> hs = new HashSet<String>(); Queue<String> queue = new LinkedList<String>(); boolean find = false; queue.offer(s); hs.add(s); while (! queue.isEmpty()) { String str = queue.poll(); if (isValid(str)) { result.add(str); find = true; } if (find) { continue; } for (int i = 0; i < str.length(); i++) { if (str.charAt(i) != '(' && str.charAt(i) != ')') { continue; } String tmp = str.substring(0, i) + str.substring(i + 1); if (! hs.contains(tmp)) { //记录已经添加到队列的元素,防止重复计算。 hs.add(tmp); queue.offer(tmp); } } } return result; } public boolean isValid(String str) { int count = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '(') { count++; } else if (str.charAt(i) == ')') { if (count > 0) { count--; } else { return false; } } } return count == 0; }
相关文章推荐
- Ceph mon一个故障案例的处理
- [LeetCode] Game of Life
- shell监控MySQL服务是否正常
- poj--3207--Ikki's Story IV - Panda's Trick(2-sat)
- Centos7无法使用ssh登陆及解决方案
- spring mvc 表单提交,试过可用
- 单例模式的七种写法
- 异步选择模型WSAAsyncSelect
- 卷积神经网络学习笔记(一)
- 【Android开发—智能家居系列】(四):UDP通信发送指令
- 【安卓网络编程】Android Studio导入Volley
- poj--3207--Ikki's Story IV - Panda's Trick(2-sat)
- 选择排序
- [Leetcode]Sqrt(x)
- 编译安装memcached时提示找不到gcc
- 忆往昔,看今朝
- Mac及Xcode常用快捷键
- Foudation框架内的函数和方法
- UITableViewCell的样式
- Nutch2.3 + Hbase 配置到爬行