Skip to content

Commit 68dc1a2

Browse files
authored
Create remove-sub-folders-from-the-filesystem.cpp
1 parent 4e0ad4e commit 68dc1a2

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Time: O(n), n is the total sum of the lengths of folder names
2+
// Space: O(t), t is the number of nodes in trie
3+
4+
class Solution {
5+
public:
6+
vector<string> removeSubfolders(vector<string>& folder) {
7+
TrieNode trie;
8+
for (const auto& s : folder) {
9+
trie.Insert(split(s, '/'));
10+
}
11+
vector<string> result;
12+
vector<string> path;
13+
dfs(&trie, &path, &result);
14+
return result;
15+
}
16+
17+
private:
18+
struct TrieNode {
19+
bool is_end = false;
20+
unordered_map<string, TrieNode *> leaves;
21+
22+
void Insert(const vector<string>& s) {
23+
auto* p = this;
24+
for (const auto& c : s) {
25+
if (c.empty()) {
26+
continue;
27+
}
28+
if (!p->leaves.count(c)) {
29+
p->leaves[c] = new TrieNode;
30+
}
31+
p = p->leaves[c];
32+
}
33+
p->is_end = true;
34+
}
35+
36+
~TrieNode() {
37+
for (auto& kv : leaves) {
38+
if (kv.second) {
39+
delete kv.second;
40+
}
41+
}
42+
}
43+
};
44+
45+
void dfs(TrieNode *curr, vector<string> *path, vector<string> *result) {
46+
if (curr->is_end) {
47+
result->emplace_back(join(*path, '/'));
48+
return;
49+
}
50+
for (const auto& kvp : curr->leaves) {
51+
path->emplace_back(kvp.first);
52+
dfs(kvp.second, path, result);
53+
path->pop_back();
54+
}
55+
}
56+
57+
vector<string> split(const string& s, const char delim) {
58+
vector<string> result;
59+
auto end = string::npos;
60+
do {
61+
const auto& start = end + 1;
62+
end = s.find(delim, start);
63+
result.emplace_back(s.substr(start, end - start));
64+
} while (end != string::npos);
65+
return result;
66+
}
67+
68+
string join(const vector<string>& names, const char delim) {
69+
string result;
70+
for (const auto& name : names) {
71+
result.push_back('/');
72+
result += name;
73+
}
74+
return result;
75+
}
76+
};

0 commit comments

Comments
 (0)