-
Notifications
You must be signed in to change notification settings - Fork 7
/
RemoveInvalidParentheses.cpp
82 lines (74 loc) · 2.88 KB
/
RemoveInvalidParentheses.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
// Problem: https://leetcode.com/problems/remove-invalid-parentheses/
#include<string>
#include<vector>
using namespace std;
class RemoveInvalidParentheses {
public:
vector<string> removeInvalidParentheses(string s) {
string expression;
string s1 = trimBraces(s);
this->recurse(s1, expression, 0, 0, 0, 0);
return uniqify(this->_solutions);
}
private:
string trimBraces(string s) {
string s1 = s;
int index = s1.size() - 1;
while (index >= 0) {
char curr_ch = s1[index];
if (curr_ch == ')') break;
if (curr_ch == '(') s1.erase(index, 1);
--index;
}
return s1;
}
vector<string> uniqify(const vector<string>& vec) {
unordered_set<string> s;
vector<string> vec_s;
for (int i = 0; i < vec.size(); ++i) {
if (s.find(vec[i]) == s.end()) {
vec_s.push_back(vec[i]);
s.insert(vec[i]);
}
}
return vec_s;
}
void recurse(string s, string& expression, int index, int r_count, int l_count, int num_removals) {
// Case-I: If this is the end of the string.
if (index == s.size()) {
// Check if this is a valid string.
if (l_count == r_count) {
// Reset, if the number of removals is less.
if (num_removals < this->_min_removals) {
this->_min_removals = num_removals;
this->_solutions.clear();
}
// Update the solution set with the current solution.
if (num_removals == this->_min_removals) {
this->_solutions.push_back(expression);
}
}
} else {
char curr_char = s.at(index);
// Case-II: Skip over non-brackets.
if (curr_char != '(' && curr_char != ')') {
expression.append(1, curr_char);
this->recurse(s, expression, index + 1, r_count, l_count, num_removals);
expression.erase(expression.size() - 1 /* Index */, 1 /* Length */);
} else {
// Case-III: Delete a bracket and try.
this->recurse(s, expression, index + 1, r_count, l_count, num_removals + 1);
expression.append(1, curr_char);
// Case-IV: Accept an opening brace.
if (curr_char == '(') {
this->recurse(s, expression, index + 1, r_count, l_count + 1, num_removals);
} else if (l_count > r_count) { // Case-V: Accept a closing brace.
this->recurse(s, expression, index + 1, r_count + 1, l_count, num_removals);
}
expression.erase(expression.size() - 1 /* Index */, 1 /* Length */);
}
}
}
int _min_removals = INT_MAX;
vector<string> _solutions;
};