# LeetCode Remove Invalid Parenthese

79人阅读 评论(0)

LeetCode 每日刷题！！

Remove Invalid Parentheses

#include <iostream>
#include <stdio.h>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <unordered_set>
#include <queue>
#include <stack>
#include <assert.h>
#include <set>
using namespace std;

class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
set<string> visited;
string *current = &s;
vector<string> ans;
vector<string> layerSet;
vector<string> nextlayer;
if (s == "")
{
ans.push_back("");
return ans;
}
layerSet.push_back(s);

while (layerSet.size() != 0)
{
//each layer of a BFT, the optimize have the least delete number
//and each loop have the same delete num.
for (int i = 0; i < layerSet.size(); i++)
{
*current = layerSet[i];
if (isValid(*current))
{
ans.push_back(*current);
}

}
if (ans.size() != 0)
{
return ans;
}
for (int i = 0; i < layerSet.size(); i++)
{
*current = layerSet[i];
for (int i = 0; i < current->size(); i++)
{
if ((*current)[i] != '(' && (*current)[i] != ')')
{
continue;
}
string tmp = current->substr(0, i) + current->substr(i + 1);
if (tmp == "")
{
ans.push_back("");
return ans;
}

if (visited.find(tmp) == visited.end())
{
nextlayer.push_back(tmp);
visited.insert(tmp);
}

}
}
layerSet.swap(nextlayer);

}
return ans;
}

bool isValid(string s)
{
int num = 0;
if (s.size() == 0)
{
return false;
}
for (int i = 0; i < s.size(); i++)
{
if (s[i] == '(') {
num++;
}
if (s[i] == ')') {
num--;
}
if (num < 0)
return false;
}
return num == 0;
}
};

int main()
{
string test1 = ")()m)(((()((()((((";
vector<string> ans;
Solution *solu = new Solution();
ans = solu->removeInvalidParentheses(test1);
for (int i = 0; i < ans.size(); i++)
{
cout << ans[i] << endl;
}

system("pause");
return 0;

}


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：455次
• 积分：33
• 等级：
• 排名：千里之外
• 原创：3篇
• 转载：0篇
• 译文：0篇
• 评论：0条
文章分类
文章存档
阅读排行