这个就是字典树了,我用unordered_map时间上更节省一些。
class TrieNode {
public:
unordered_map<char,TrieNode *> children;
bool isLeaf;
TrieNode(){isLeaf = false;};
};
class Trie {
public:
TrieNode *root;
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode *cur = root;
for (int i = 0;i<word.size();i++) {
if(cur->children.find(word[i]) == cur->children.end()) {
cur->children[word[i]] = new TrieNode();
}
cur = cur->children[word[i]];
}
cur->isLeaf = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode *cur = root;
for (int i = 0;i<word.size();i++) {
if(cur->children.find(word[i]) == cur->children.end()) {
return false;
}
cur = cur->children[word[i]];
}
if(cur->isLeaf) return true;
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode *cur = root;
for (int i = 0;i<prefix.size();i++) {
if(cur->children.find(prefix[i]) == cur->children.end()) {
return false;
}
cur = cur->children[prefix[i]];
}
return true;
}
};

本文介绍了一种使用C++实现的字典树(Trie)数据结构,通过`unordered_map`来优化时间效率。该实现支持单词插入、搜索及前缀匹配等功能。

530

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



