removeInvalidParentheses
来源:互联网 发布:淘宝打假赚钱 编辑:程序博客网 时间:2024/06/16 12:54
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())()"]")(" -> [""]
先占个坑,实现了一个naive版本的。dfs的时候把不符合条件的结果也保存进去了,需要过滤一下,而且是用的set去重。看网上对于统计有一种方法跟我之前想的很类似。对于
")()(" 这种情况网上给出了先预处理左边跟右边的这种情况,我觉得是合理的其他的应该可以通过维护两个left, right变量,表示左边右边一共可以使用的括号数来进行拼接。以后补上。
代码:
public List<String> removeInvalidParentheses(String s) { if(s == null) return new ArrayList<>(); if(s.length() == 0){ List<String> ret = new ArrayList<>(); ret.add(""); return ret; } HashSet<String> result = new HashSet<>(); dfs(result, s, "", 0, 0, 0); //需要找到最长的那种情况,过滤一下 // List<String> answer = new ArrayList<>(result).stream().filter(str -> str.length() == maxLength).collect(Collectors.toList()); List<String> answer = new ArrayList<>(); for(String item: result){ if(item.length() == maxLength){ answer.add(item); } } if(answer.size() == 0){ answer.add(""); } return answer; } private int maxLength = Integer.MIN_VALUE; private void dfs(HashSet<String> result, String s, String cur, int left, int right, int index){ if(index == s.length()){ if(left == right && cur.length() != 0){ result.add(cur); maxLength = Math.max(maxLength, cur.length()); } return; } char ch = s.charAt(index); if(!isParen(ch)){ dfs(result, s, cur+ch, left, right, index+1); }else{ if(ch == '('){ dfs(result, s, cur+"(", left+1, right, index+1); } if(ch == ')'){ if( right < left){ dfs(result, s, cur+")", left, right+1, index+1); } } dfs(result, s, cur, left, right, index+1); } } private boolean isParen(char ch){ return ch == '(' || ch == ')'; }
0 0
- removeInvalidParentheses
- 解决 ajax请求 跨域问题
- 嵌入式学习笔记之gcc编译
- screen capture using CGDisplayStreamCreateWithDispatchQueue
- Redis数据库的备份与恢复
- layer中type=2的一些使用方法(添加成功后才关闭路由、刷新页面列表)
- removeInvalidParentheses
- opencv学习笔记(十)画直线、矩形、圆形、椭圆以及多边形程序
- css 样式中类之间有空格和无空格的区别
- Android图片加载神器之Fresco-加载图片基础[详细图解Fresco的使用]
- Android多进程实现及常见问题
- select下拉框搜索回显搜索条件
- android之相机开发
- 文章标题
- SRT上传文件下载文件