【LeetCode】301. Remove Invalid Parentheses
来源:互联网 发布:网络作家富豪榜 2016 编辑:程序博客网 时间:2024/05/01 15:09
题目:
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来求解这道题。
每次将队列中第一个元素出队并判断其是否是有效的字符串,若是就加入结果向量result中,若不是则将该字符串删去一个括号的子串加入队列中。由于使用BFS算法,当找到一个有效的字符串后就不用继续寻找下去,因为之后添加的字符串删去的括号数一定大于最小的,不满足条件。
代码:
class Solution {public: bool valid(string s) //判断字符串是否有效 { int count = 0; for(int i = 0;i<s.length();i++) { if(s[i] == '(') count++; else if(s[i] == ')') count--; if(count<0) return false; } if(count!=0) return false; return true; } vector<string> removeInvalidParentheses(string s) { vector<string> result; queue<string> q; set<string> visited; q.push(s); visited.insert(s); set<string>::iterator it; int tag = 0; while(!q.empty()) { string temp = q.front(); q.pop(); if(valid(temp)) { result.push_back(temp); tag = 1; } if(tag == 0) //还没有找到有效的字符串 { for(int i = 0;i<temp.length();i++) { if(temp[i]!='('&&temp[i]!=')') continue; string tp = temp.substr(0,i)+temp.substr(i+1,temp.length()); it = visited.find(tp); if(it == visited.end()) //没有遍历过 { q.push(tp); visited.insert(tp); } } } } return result; }};
0 0
- 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
- leetcode 301. Remove Invalid Parentheses
- [leetcode]301. Remove Invalid Parentheses
- Leetcode: 301.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
- RTSP 协议 简单交互过程
- [心得]面试题分析与整理3
- 使用FragmentTabHost实现类似微信底部的效果
- 使用Pollard rho算法计算两个大整数的最小公倍数
- tomcat在Debug模式下无法启动解决办法
- 【LeetCode】301. Remove Invalid Parentheses
- 最轻的天平
- 一个关于指针数组的例子
- 【JAVA设计模式】——设计原则
- caffe学习系列四Sigmod、Tanh、ReLU等Layer源码分析
- 杭电ACM2004题(成绩转换)-----C语言
- 中文在URL中的编码
- NuPlayer介绍
- hdu 1422 重温世界杯【思维】