301. Remove Invalid Parentheses
来源:互联网 发布:gta5帧数优化提高帧数 编辑:程序博客网 时间:2024/06/10 00:50
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
import java.util.ArrayList;import java.util.HashSet;import java.util.LinkedList;import java.util.List;import java.util.Queue;import java.util.Set;/* * BFS solution */public class Solution { public List<String> removeInvalidParentheses(String s) { List<String> rst = new ArrayList<String>(); Set<String> visited = new HashSet<String>(); Queue<String> queue = new LinkedList<String>(); Queue<String> queue2 = new LinkedList<String>(); queue.add(s); visited.add(s); boolean found = false; while(!queue.isEmpty()) { String ss = queue.remove(); if(isValid(ss)) { rst.add(ss); found = true; } if(!found) { for(int i=0; i<ss.length(); i++) { String t = ss.substring(0, i) + ss.substring(i+1); if(!visited.contains(t)) { queue2.add(t); visited.add(t); } } } if(queue.isEmpty()) { if(found)break; queue = queue2; queue2 = new LinkedList<String>(); } } return rst; } public boolean isValid(String s) { char[] cs = s.toCharArray(); int cnt = 0; for(char c : cs) { if(c == '(')cnt++; if(c == ')')cnt--; if(cnt < 0)return false; } return cnt == 0; }}
0 0
- 301. Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- 301. Remove Invalid Parentheses
- 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
- 【LeetCode】301. Remove Invalid Parentheses
- [LeetCode]301. Remove Invalid Parentheses
- Leetcode 301. Remove Invalid Parentheses
- 送给进入到计算机世界的自己
- 《道德经》第九章
- 深入浅出JMS(一)--JMS基本概念
- Python命名空间的本质
- 数据结构和算法分析学习笔记
- 301. Remove Invalid Parentheses
- #我的2016#梁定郊和我的江浙行分享贿赠同行友谊
- .Net程序员学用Oracle系列(16):访问数据库(ODP.NET)
- Stone的txl数
- Go 1.8中值得关注的几个变化
- dom4j 复制xml文件/复制xml文件中选中节点到另一个xml文件
- 开源播放框架ijkplayer(iOS版)使用教程
- HDU - 1067 Gap (bfs + hash) [kuangbin带你飞]专题二
- mssql_fetch_row与mssql_fetch_array的区别