以LeetCode 208. 实现 Trie (前缀树)为例。
https://leetcode-cn.com/problems/implement-trie-prefix-tree/
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 true
trie.search("app"); // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");
trie.search("app"); // 返回 true
说明:
- 你可以假设所有的输入都是由小写字母 a-z 构成的。
- 保证所有输入均为非空字符串。
【笔记】核心在于struct TrieNode
结构体的设计。楼上@Asapine 的C++
版本已经写的很好了,再此基础上,我将其改成了智能指针。以下部分的private
内容为辅助函数、成员变量。
class Trie {
public:
Trie() : root_(std::make_shared<TrieNode>()) {
}
void insert(string word) {
auto res = root_;
for (auto c : word) {
if (res->children_[c-'a'] == nullptr) {
res->children_[c-'a'] = std::make_shared<TrieNode>();
}
res = res->children_[c-'a'];
}
res->isWord_ = true;
}
bool search(string word) {
std::shared_ptr<TrieNode> res = find(word);
return res != nullptr && res->isWord_ == true;
}
bool startsWith(string prefix) {
return find(prefix) != nullptr;
}
private:
struct TrieNode{
TrieNode() : isWord_(false), children_(26, nullptr) {
}
bool isWord_;
vector<std::shared_ptr<TrieNode>> children_;
};
std::shared_ptr<TrieNode> find(string& prefix) {
auto res = root_;
for (int i = 0; i < prefix.size() && res != nullptr; ++i) {
res = res->children_[prefix[i]-'a'];
}
return res;
}
std::shared_ptr<TrieNode> root_;
};
2019-2-20 北京 海淀