-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path301. Remove Invalid Parentheses.cpp
98 lines (64 loc) · 1.73 KB
/
301. Remove Invalid Parentheses.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class Solution {
bool valid(string &str) {
stack<char> s;
for(auto c: str) {
if (c == '(')
s.push(c);
else if(isalpha(c)) {
// do nothing
}
else if (c == ')') {
if (!s.empty() && s.top() == '(')
s.pop();
else
return false;
}
}
if (s.empty())
return true;
else
return false;
}
void process(string &s, queue<string> &q, unordered_set<string> &visited) {
int n = s.length();
for(int i = 0;i<n;++i) {
if(s[i]!='(' && s[i]!=')')
continue;
string temp = s.substr(0,i) + s.substr(i+1);
if(visited.find(temp) == visited.end()) {
q.push(temp);
visited.insert(temp);
}
}
}
public:
vector<string> removeInvalidParentheses(string s) {
queue<string> q;
vector<string> result;
unordered_set<string> visited;
bool ans = false;
if (valid(s)) {
result.push_back(s);
return result;
}
q.push(s);
visited.insert(s);
while(!q.empty()) {
int count = q.size();
while(count--) {
string top = q.front();
q.pop();
if (valid(top)) {
ans = true;
result.push_back(top);
}
process(top, q, visited);
}
if (ans)
break;
}
if (result.empty())
result.push_back("");
return result;
}
};