Remove Invalid Parentheses
Thoughts
Code
class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
vector<string> res;
queue<string> q;
q.push(s);
bool found = false;
unordered_set<string> visited;
while (!q.empty()) {
const auto size = q.size();
for (int i = 0; i < size; ++i) {
string s = q.front();
q.pop();
if (visited.find(s) != visited.end()) continue;
visited.insert(s);
if (valid(s)) {
res.push_back(s);
found = true;
continue;
}
if (!found) {
for (int j = 0; j < s.size(); ++j) {
if (s[j] != '(' && s[j] != ')') continue;
q.push(s.substr(0, j).append(s.substr(j + 1, s.size())));
}
}
}
}
return res;
}
private:
bool valid(string s) {
int val = 0;
for (const auto c : s) {
if (c == '(') ++val;
if (c == ')') --val;
if (val < 0) return false;
}
return val == 0;
}
};Analysis
Last updated