【Leetcode】Remove Invalid Parentheses
来源:互联网 发布:淘宝客服要求 编辑:程序博客网 时间:2024/05/16 04:54
题目链接: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())()”]
“)(” -> [“”]
思路:
暴力遍历 所有 删除该字符串一部分后的结果(一个个的删),若为为有效字符串则保留结果退出递归。 为了优化递归 对于没必要继续递归的分支进行剪枝。
那么哪些是没有必要递归的呢? 这就要计算当前字符串有多少个无效字符了,比如))(就是3,())就是1,用栈就能得到结果了。 当删除当前字符串某个字符后,若删除前字符的无效字符数 大于 删除后的无效字符数,则说明当前删除的字符是可以减少无效字符的,所以就往这个方向继续递归。 否则就没要继续递归了~~
又因为字符串是一个个逐个递归删除的,当遇到一个字符串的无效字符数为0的时候它当然就是最长的有效字符串~
算法:
List<String> res = new ArrayList<String>(); public List<String> removeInvalidParentheses(String s) { dsp(s); return res; } Set<String> maps = new HashSet<String>(); public void dsp(String s){ int min = cals(s); if(min==0){ res.add(s); return; } for(int i=0;i<s.length();i++){ String next = s.substring(0,i)+s.substring(i+1,s.length()); if(!maps.contains(next)&&cals(next)<min){ maps.add(next); dsp(next); } } } public int cals(String s){ Stack<Character> stack = new Stack<Character>(); for(int i=0;i<s.length();i++){ char c = s.charAt(i); if(c!='('&&c!=')') continue; if(stack.isEmpty()){ stack.push(c); continue; } if(c=='('){ stack.push(c); }else if(c==')'){ if(stack.peek()=='('){ stack.pop(); }else{ stack.push(c); } } } return stack.size(); }
1 0
- [LeetCode] Remove Invalid Parentheses
- LeetCode -- Remove Invalid Parentheses
- leetcode Remove Invalid Parentheses
- LeetCode Remove Invalid Parentheses
- [Leetcode]Remove Invalid Parentheses
- leetcode:Remove Invalid Parentheses
- leetcode - Remove Invalid Parentheses
- 【Leetcode】Remove Invalid Parentheses
- LeetCode:Remove Invalid Parentheses
- Remove Invalid Parentheses -- Leetcode
- [LeetCode]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
- Android_Service多线程断点下载
- 电商之梳理项目nexus的maven部署---jar包管理工具
- Android View中getViewTreeObserver().addOnGlobalLayoutListener()
- oracle——Hibernate 不同数据库的连接及SQL方言
- 真机、虚拟机串口通信
- 【Leetcode】Remove Invalid Parentheses
- 电商之梳理jenkins相关知识---web部署工具
- 电商之梳理GIT相关知识---代码管理工具
- 面试:字符串: 字符串转换为10进制数
- QT编程中mysql数据库的时间、日期的运用
- mysql和mariadb主库drop表时从库的不同处理方式
- 如何在CentOS-6.5-x86_64安装Git
- 电商之梳理jsp相关知识---前端技术
- 数组整理