题目:
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;
}
};