301. Remove Invalid Parentheses
2022/4/7 6:20:47
本文主要是介绍301. Remove Invalid Parentheses,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Just use BFS to solve this problem:
1. put the s to queue
2. if s is not a valid string, then remove a '(' or ')', and then put to the queue.
3. once find valid strings, return.
class Solution { public List<String> removeInvalidParentheses(String s) { Set<String> res = new HashSet<>(); Queue<String> queue = new LinkedList<>(); queue.offer(s); Set<String> visited = new HashSet<>(); visited.add(s); while(!queue.isEmpty()){ int size = queue.size(); for(int i=0;i<size;i++){ String str = queue.poll(); if(isValid(str)){ res.add(str); } else{ for(int j=0;j<str.length();j++){ String temp = str.substring(0, j)+str.substring(j+1); if(!visited.contains(temp)){ visited.add(temp); queue.offer(temp); } } } } if(res.size()>0) return new ArrayList(res); } return new ArrayList(res); } private boolean isValid(String s){ int count = 0; for(int i=0;i<s.length();i++){ if(s.charAt(i)=='(') count++; else if(s.charAt(i)==')'){ if(count>0) count--; else return false; } } return count==0; } }
这篇关于301. Remove Invalid Parentheses的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?