0%

1233. Remove Sub-Folders from the Filesystem

用hash table提前把所有path存起来 遍历每个path 从后往前删文件名(相当于从subfolder向上找parent folder的path)如果parent folder的path在hash table里 证明这是一个subfolder应该remove 否则将一直找到根目录的path

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
vector<string> removeSubfolders(vector<string>& folder) {
unordered_set<string_view> s(begin(folder), end(folder));
vector<string> res;
for (const auto &f : folder) {
string_view v(f);
do {
v.remove_suffix(v.length() - v.find_last_of('/'));
} while (!v.empty() && !s.count(v));
if (v.empty()) {
res.push_back(f);
}
}
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
vector<string> removeSubfolders(vector<string>& folder) {
unordered_set<string_view> s(begin(folder), end(folder));
vector<string> res;
for (const auto &f : folder) {
string_view v(f);
while (!v.empty()) {
while (v.back() != '/') {
v.remove_suffix(1);
}
v.remove_suffix(1);
if (s.count(v)) break;
}
if (v.empty()) {
res.push_back(f);
}
}
return res;
}
};

类似trie

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
class Solution {
public:
vector<string> removeSubfolders(vector<string>& folder) {
root = new Folder;
for (const auto &path : folder) {
add(path);
}
dfs(root);
return res;
}

struct Folder {
unordered_map<string, Folder *> subfolders;
string path;
};

Folder *root;

void add(const string &path) {
auto p = root;
istringstream input(path);
string name;
while (getline(input, name, '/')) {
if (!p->subfolders.count(name)) {
p->subfolders[name] = new Folder;
}
p = p->subfolders[name];
}
p->path = path;
}

void dfs(Folder *p) {
if (!p->path.empty()) {
res.push_back(p->path);
return;
}
for (auto &[_, subfolder] : p->subfolders) {
dfs(subfolder);
}
}

vector<string> res;
};