#define MAX_SIZE 26
class TrieNode {
public:
TrieNode *child[MAX_SIZE];
bool isWord;
TrieNode() : isWord(false){
for (int i=0;i<MAX_SIZE;i++)
child[i]=NULL;
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
void insert(string s) {
TrieNode *p = root;
for (int i=0;i<s.length();i++) {
int id = s[i] - 'a';
if (!p->child[id])
p->child[id] = new TrieNode();
p = p->child[id];
}
p->isWord = true;
}
bool search(string key) {
TrieNode *p = root;
for (int i=0;i<key.length();i++) {
int id = key[i] - 'a';
if (!p->child[id])
return false;
p = p->child[id];
}
return p->isWord;
}
//和search()几乎一样,只是最后返回值不一样
bool startsWith(string prefix) {
TrieNode *p = root;
for (int i=0;i<prefix.length();i++) {
int id = prefix[i] - 'a';
if (!p->child[id])
return false;
p = p->child[id];
}
return true;
}
private:
TrieNode* root;
};
网友评论