-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathBrace Expansion II.cpp
72 lines (70 loc) · 2.26 KB
/
Brace Expansion II.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
// Runtime: 7 ms (Top 85.26%) | Memory: 10.50 MB (Top 92.63%)
class Solution {
public:
void getUnion(vector<string>& a, const vector<string>& b) {
if (!a.size()) {
a = b;
return;
}
for (const auto& str_b: b) {
bool found = false;
for (const auto& str_a: a) {
if (str_a == str_b) {
found = true;
break;
}
}
if (!found) a.push_back(str_b);
}
}
void getComb(vector<string>& a, const vector<string>& b) {
if (!a.size()) {
a = b;
return;
}
vector<string> tmp;
for (const auto& str_a: a) {
for (const auto& str_b: b) {
tmp.push_back(str_a + str_b);
}
}
a = tmp;
}
vector<string> braceExpansionII(string expression) {
if (expression.size() == 0) return {};
if (expression.size() == 1) return {expression};
int n = expression.size();
vector<string> ans;
vector<string> processing_str;
int in_brace = 0;
string partial_str{};
for (int i = 0; i < n; ++ i) {
if (expression[i] == '{') {
if (in_brace) partial_str += expression[i];
in_brace ++;
} else if (expression[i] == '}') {
in_brace --;
if (in_brace) partial_str += expression[i];
if (!in_brace) {
getComb(processing_str, braceExpansionII(partial_str));
partial_str.clear();
}
} else if (in_brace == 0 && expression[i] == ',') {
getUnion(ans, processing_str);
processing_str.clear();
partial_str.clear();
} else if (in_brace == 0) {
std::string tmp = "";
while (i < n && expression[i] >= 'a' && expression[i] <= 'z')
tmp += expression[i++];
-- i;
getComb(processing_str, {tmp});
} else {
partial_str += expression[i];
}
}
getUnion(ans, processing_str);
sort(ans.begin(), ans.end());
return ans;
}
};