(1) 字典树。
(2) 是否word;
class TrieNode{
public:
TrieNode* child[26];
bool isWord;
TrieNode():isWord(false) {
for(int i=0;i<26;i++)
child[i] = NULL;
}
};
class Trie {
TrieNode* mRoot;
public:
/** Initialize your data structure here. */
Trie() {
mRoot = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode *p = mRoot;
for (auto &a : word) {
int i = a - 'a';
if (!p->child[i]) p->child[i] = new TrieNode();
p = p->child[i];
}
p->isWord = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode* cur = mRoot;
for(int i=0;i<word.size();i++) {
int index = word[i]-'a';
if(!cur->child[index])
return false;
cur = cur->child[index];
}
return cur->isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode* cur = mRoot;
for(int i=0;i<prefix.size();i++) {
int index = prefix[i]-'a';
if(!cur->child[index])
return false;
cur = cur->child[index];
}
return true;
}
};