原题链接在这里:https://leetcode.com/problems/remove-invalid-parentheses/

题目:

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())()"]
")(" -> [""]

题解:

题目要求减少最小个数的非法括号,要求最小,就想到BFS.

Queue 里加入 原来的string s, 循环中从queue中poll出来一个string. 每次减掉一个括号,若是合法了就加到res中,同时停止继续enqueue, 只把queue中现有的一个level检查了就好。

若是没遇到合法的,就把str从头到尾减掉一个括号放回到queue中。

检查是否合法用isValid. 这种写法不需要stack, 节省了空间。

同时使用Set 来记录已经检查过的string, 检查过就不需要再次检查。

Time Complexity: exponential. n = s.length(). Space: O(n).

AC Java:

 public class Solution {
public List<String> removeInvalidParentheses(String s) {
List<String> res = new ArrayList<String>();
if(s == null){
return res;
} LinkedList<String> que = new LinkedList<String>();
HashSet<String> visited = new HashSet<String>(); //存储已经检查过的string, 没有必要重复检查
que.add(s);
visited.add(s);
boolean found = false; //标签,检查是否找到了valid parentheses while(!que.isEmpty()){
String str = que.poll();
if(isValid(str)){
res.add(str);
found = true;
}
if(found){ //已经找到,就在本level中找剩下的就好了
continue;
}
for(int i = 0; i<str.length(); i++){
if(str.charAt(i) != '(' && str.charAt(i) != ')'){
continue;
}
String newStr = str.substring(0,i) + str.substring(i+1);
if(!visited.contains(newStr)){
que.add(newStr);
visited.add(newStr);
}
}
}
return res;
} private boolean isValid(String s){
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;
}else{
count--;
}
}
}
return count == 0;
}
}

类似Minimum Remove to Make Valid Parentheses.

最新文章

  1. .net(c#)版RSA加密算法,拿走不谢
  2. (五)SQL Server分区自动化案例
  3. 清空StringBuilder的三种方法及效率
  4. canvas 实现 柱状图
  5. Extract QQ from iPhone and analyze it
  6. correctly handle PNG transparency in Win IE 5.5 &amp; 6.
  7. C# 加密解密
  8. HDU 4906 状态压缩dp
  9. setbuffer和freopen做一个简单的日志组件
  10. 【我们都爱Paul Hegarty】斯坦福IOS8公开课个人笔记2 Xcode、Auto Layout及MVC
  11. Python 3.5 for windows 10 通过pip安装mysqlclient模块 error:C1083
  12. Hadoop 中 Eclipse 的配置
  13. fatal error RC1004: unexpected end of file found处理方法
  14. CSS3秘笈:第三章
  15. Bootstrap3 代码-变量
  16. Python基础(文件操作)
  17. IP核引发的关于定,浮点数的认识
  18. 在linux下面解压用的zxpf是什么意思,它跟zxvf有啥区别
  19. c++试题2
  20. 移动web总结

热门文章

  1. 『cdq分治和多维偏序问题』
  2. C#子线程执行完后,调用主线程的方法
  3. latex设置不同中英文字体
  4. 关于vs无法创建虚拟目录的问题
  5. Gearman介绍、原理分析、实践改进
  6. [C++] 初始化 vs 赋值
  7. pickle导入变量AttributeError的解决方案
  8. echarts自定义悬浮框的显示
  9. ajax往后台传值的一些方式
  10. CSS 标签显示模式