字典树(TrieTree)
简介
字典树(前缀树)是字符串匹配问题的常用算法之一,是KMP算法的升级版本,KMP解决单一字符串匹配问题效果极佳,但是对于多个字符串匹配的问题,需要使用字典树效果才显著。
代码
#include <bits/stdc++.h>
using namespace std;
const int NUM = 26;
typedef struct TrieNode{
bool isWord;
struct TrieNode *next[NUM];
TrieNode() :isWord(false){
memset(next,(int)NULL,sizeof(next));
}
} TrieNode;
class Trie{
private:
TrieNode *root;
public:
Trie(){
root = new TrieNode();
}
void Insert(string& word){
TrieNode *location = root;
for (int i = 0;i < (int)word.size();++i){
if (location->next[word[i] - 'a'] == nullptr){
TrieNode *temp = new TrieNode();
location->next[word[i] - 'a'] = temp;
}
location = location->next[word[i] - 'a'];
}
location->isWord = true;
return ;
}
bool Search(string& word){
TrieNode *location = root;
for (int i = 0;i < (int)word.size() && location;++i){
location = location->next[word[i] - 'a'];
}
return (location != nullptr && location->isWord);
}
bool StartWith(string& prefix){
TrieNode *location = root;
for (int i = 0;i < (int)prefix.size();++i){
location = location->next[prefix[i] - 'a'];
if (location == nullptr) return false;
}
return true;
}
void DeleteTrie(TrieNode *root){
for (int i = 0;i < NUM;++i){
if (root->next[i] != nullptr) DeleteTrie(root->next[i]);
}
delete root;
}
};
int main(void){
// vector<string> v{"abc","ab","abdf","cdd"};
vector<string> v{"","","a",""};
string word = "";
Trie tree;
for (int i = 0;i < (int)v.size();++i){
tree.Insert(v[i]);
}
cout << tree.Search(word) << endl;
return 0;
}