// leetcode 1233 前缀字典树
// 建个前缀字典树,在文件末尾添加'/'当结束
// 一道笔试题,但当时没写出来字典树,总是事后诸葛亮。。。
// 此模板自己演算,这种东西还是按照想法来,不要背,亲自演算,下次不慌
// 加油鸭
class Trie {
public:
bool isEnd;
Trie* alp[28];
Trie() {
isEnd = false;
fill(alp, alp + 28, nullptr);
}
static bool insert(Trie* &root, const string &s) {
Trie* p = root;
for (int i = 0; i < s.size(); i++) {
int c = s[i] - 'a';
if (s[i] == '/') c = 27;
if (p->isEnd)
return false;
if (p->alp[c] == nullptr) {
Trie* nxt = new Trie();
p->alp[c] = nxt;
}
p = p->alp[c];
}
p->isEnd = true;
return true;
}
};
class Solution {
public:
vector<string> removeSubfolders(vector<string>& folder) {
sort(folder.begin(), folder.end());
Trie* root = new Trie();
vector<string> ans;
for (int i = 0; i < folder.size(); i++) {
string s = folder[i];
s += '/';
if (Trie::insert(root, s)) {
ans.emplace_back(folder[i]);
}
}
return ans;
}
};
leetcode 1233 前缀字典树
最新推荐文章于 2024-03-22 00:51:13 发布
本文介绍了如何使用前缀字典树(Trie)数据结构解决一道笔试题,即在给定的文件夹路径列表中去除子文件夹。通过构建Trie并插入路径,可以有效检测重复的子文件夹,并返回唯一的文件夹路径。这种方法有助于理解Trie数据结构及其在路径去重问题中的应用。

8345

被折叠的 条评论
为什么被折叠?



