删除子文件夹
1. 问题描述
题目链接:删除子文件夹

2. 思路
看到公共前缀,考虑用字典树,对于该题,需要对每个节点额外开辟一个标志位end,以标记是否为完整路径结束。
字典树结构如下
点击查看代码
struct Node {
int end;
unordered_map<string, Node*> next;
Node() {
end = 0;
};
};
class Trie {
public:
Trie() {
root = new Node();
};
void insert(vector<string>& words) {};
bool search(vector<string>& words) {};
private:
Node* root;
};
3. 完整代码
点击查看代码
struct Node {
int end;
unordered_map<string, Node*> next;
Node() {
end = 0;
};
};
class Trie {
public:
Trie() {
root = new Node();
};
void insert(vector<string>& words) {
Node* cur = root;
for (auto word : words) {
if (cur->next.find(word) == cur->next.end()) {
cur->next[word] = new Node();
}
cur = cur->next[word];
}
cur->end = 1;
}
bool search(vector<string>& words) {
Node* cur = root;
for(int i = 0; i < words.size(); i++) {
cur = cur->next[words[i]];
if(i < words.size() - 1 && cur->end) return true; // 前缀不能是word数组本身
}
return false;
}
private:
Node* root;
};
class Solution {
public:
vector<string> split(string& s, char delim) {
stringstream ss(s);
string item;
vector<string> res;
while (getline(ss, item, delim)) {
res.emplace_back(item);
}
return res;
}
vector<string> removeSubfolders(vector<string>& folder) {
int n = folder.size();
vector<int> flag(n);
Trie* trie = new Trie();
vector<vector<string>> paths;
for (int i = 0; i < n; ++i) {
vector<string> path = split(folder[i], '/');
paths.push_back(path);
trie->insert(path);
}
for (int i = 0; i < n; ++i) {
if (trie->search(paths[i])) {
flag[i] = 1;
}
}
vector<string> ans;
for(int i = 0; i < n; i++) {
if(!flag[i]) ans.push_back(folder[i]);
}
return ans;
}
};
4. 执行结果


1233_删除子文件夹
浙公网安备 33010602011771号