题目描述:
Implement a trie with insert
, search
, and startsWith
methods.
Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true
Note:
- You may assume that all inputs are consist of lowercase letters
a-z
. - All inputs are guaranteed to be non-empty strings.
实现一颗前缀树,并实现相关的数据结构函数。对于存储单词的前缀树,如果一个节点表示一个单词,那么它的祖先表示的就是这个单词的前缀,按照层数的增加依次增加字母。另外前缀树的根节点不表示单词,简单的方法是给每个节点定义26个子节点,分别表示从当前节点代表的前缀延伸的前缀或单词。
class TrieNode {
public:
bool isWord;
TrieNode* child[26];
TrieNode(){
isWord=false;
for(int i=0;i<26;i++) child[i]=NULL;
}
};
class Trie {
public:
/** Initialize your data structure here. */
Trie() {}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode* p=root;
for(int i=0;i<word.size();i++)
{
int j=word[i]-'a';
if(p->child[j]==NULL) p->child[j]=new TrieNode();
p=p->child[j];
}
p->isWord=true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode* p=root;
for(int i=0;i<word.size();i++)
{
int j=word[i]-'a';
if(p->child[j]==NULL) return false;
else p=p->child[j];
}
return p->isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode* p=root;
for(int i=0;i<prefix.size();i++)
{
int j=prefix[i]-'a';
if(p->child[j]==NULL) return false;
else p=p->child[j];
}
return true;
}
private:
TrieNode* root=new TrieNode();
};