Trie
Trie 就是一棵字典树,根节点为空,从根节点出发到任意一个叶子节点的路径都是一个单词,也就是当前节点的父节点往上一直到根节点的路径是这个单词的前缀,每个节点分别维护一个数组记录后续子节点以及从根节点到当前节点的路径是否为一个单词。
这个题目的意思就是实现这样一棵字典树,插入一个单词,搜索一个单词,以及使用前缀搜索。
题意及条件
题目指定只包含a~z的小写字母,实现单词的插入,单词的搜索,以及前缀的搜索功能即可。
代码实现
class TrieNode {
public:
// Initialize your data structure here.
bool isWord;
vector<TrieNode*> nextNodes;
TrieNode() {
this->isWord = false;
this->nextNodes.resize(26,NULL);
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
if(word=="")
return;
TrieNode* cur=root;
for(int i=0;i<word.size();++i){
if(cur->nextNodes[word[i]-'a']!=NULL){
if(i==word.size()-1){
(cur->nextNodes[word[i]-'a'])->isWord = true;
return;
};
}else{
cur->nextNodes[word[i]-'a'] = new TrieNode() ;
if(i==word.size()-1){
(cur->nextNodes[word[i]-'a'])->isWord = true;
return;
};
}
cur = cur->nextNodes[word[i]-'a'] ;
}
}
// Returns if the word is in the trie.
bool search(string word) {
if(word=="")
return true;
TrieNode* cur = root;
for(int i=0;i<word.size();++i){
if(cur->nextNodes[word[i]-'a']!=NULL){
if(i==word.size()-1){
return (cur->nextNodes[word[i]-'a'])->isWord;
}else
cur = cur->nextNodes[word[i]-'a'];
}else
return false;
}
return false;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
if(prefix=="")
return true;
TrieNode* cur = root;
for(int i=0;i<prefix.size();++i){
if(cur->nextNodes[prefix[i]-'a']!=NULL){
if(i==prefix.size()-1){
return true;
}else
cur = cur->nextNodes[prefix[i]-'a'];
}else
return false;
}
}
private:
TrieNode* root;
};
有的同学可能会发现代码的重复,这样其实可以提供一个通用的方法,用于查找前缀,就可以大大简化上述代码。