[LeetCode] Remove Sub-Folders from the Filesystem

1233. Remove Sub-Folders from the Filesystem

Given a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order.

If a folder[i] is located within another folder[j], it is called a sub-folder of it.

The format of a path is one or more concatenated strings of the form: ‘/‘ followed by one or more lowercase English letters.

  • For example, “/leetcode” and “/leetcode/problems” are valid paths while an empty string and “/“ are not.
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
struct Trie {
unordered_map<string, Trie*> next;
bool eof = false;
string path = "";
Trie() {};

string parse(string& s, int& p) {
string res = "";
while(s.length() > p and s[p] != '/') {
res.push_back(s[p++]);
}
p++;
return res;
}
void insert(string& s, int& p) {
if(p >= s.length()) eof = true, path = s;
else {
auto token = parse(s,p);
if(!next.count(token)) next[token] = new Trie();
next[token]->insert(s, p);
}
}

void query(vector<string>& res) {
if(eof) res.push_back(path);
else {
for(auto& [_, t] : next)
t->query(res);
}
}
};

class Solution {
public:
vector<string> removeSubfolders(vector<string>& folder) {
Trie* t = new Trie();
for(auto& f : folder) {
int p = 0;
t->insert(f,p);
}
vector<string> res;
t->query(res);

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/13/PS/LeetCode/remove-sub-folders-from-the-filesystem/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.