问题描述:前缀树(字典树、单词查找树、trie树)的实现
class Trie {
bool isEnd = false;
Trie* next[26];
public:
/** Initialize your data structure here. */
Trie() {
memset(next, 0, sizeof(next));
}
/** Inserts a word into the trie. */
void insert(string word) {
Trie* node = this;
for (auto c:word)
{
if (node->next[c-'a']== nullptr)
{
node->next[c - 'a'] = new Trie();
}
node = node->next[c - 'a'];
}
node->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie* node = this;
for (auto c:word)
{
if (node->next[c-'a'] == nullptr)
{
return false;
}
node = node->next[c - 'a'];
}
return node->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie* node = this;
for (auto c: prefix)
{
if (node->next[c-'a'] == nullptr)
{
return false;
}
node = node->next[c - 'a'];
}
return true;
}
//返回与前缀prefix匹配的最后一个结点的地址
Trie* __prefix(const string& prefix) {
Trie* node = this;
for (char c : prefix) {
node = node->next[c - 'a'];
if (node == NULL) {
return NULL;
}
}
return node;
}
//获取以root为起始结点的所有单词
void __getWords(Trie* root, string& word, vector<string>& allWords) {
if (root == NULL) {
return;
}
if (root->isEnd) {
allWords.push_back(word);
}
for (int i = 0; i < 26; i++) {
word.push_back(static_cast<char>('a' + i));
__getWords(root->next[i], word, allWords);
word.pop_back();
}
}
//获取以prefix为前缀的所有单词
vector<string> getAllWordsOfPrefix(const string& prefix) {
vector<string> words;
string word = prefix;
Trie* node = __prefix(prefix);
__getWords(node, word, words);
return words;
}
//获取Trie中所有单词
vector<string> getAllWords() {
string word = "";
return getAllWordsOfPrefix(word);
}
};