您的位置:首页 > 其它

208.Implement Trie (Prefix Tree)

2015-06-30 08:48 274 查看
Implement a trie with 
insert
search
,
and 
startsWith
 methods.

Note:

You may assume that all inputs are consist of lowercase letters 
a-z
.

class TrieNode {
public:
// Initialize your data structure here.
char content;
bool isEnd;
int shared;
vector<TrieNode *> children;

TrieNode():content(' '),isEnd(false),shared(0) {

}
TrieNode(char ch):content(ch),isEnd(false),shared(0) {

}

TrieNode *subNode(char ch)
{
if(!children.empty())
{
for(auto child:children)
{
if(child->content == ch)
return child;
}
}
return NULL;
}
~TrieNode()
{
for(auto child:children)
{
delete child;
}
}

};

class Trie {
public:
Trie() {
root = new TrieNode();
}
~Trie()
{
delete root;
}

// Inserts a word into the trie.
void insert(string word) {
if(search(word))
return;
TrieNode * cur = root;
for(auto ch:word)
{
TrieNode *child = cur->subNode(ch);
if(child)
{
cur = child;
}
else
{
TrieNode *newNode = new TrieNode(ch);
cur->children.push_back(newNode);
cur = newNode;
}
++cur->shared;
}
cur->isEnd = true;

}

// Returns if the word is in the trie.
bool search(string word) {
TrieNode * cur = root;
for(auto ch:word)
{
cur = cur->subNode(ch);
if(!cur)
return false;
}
return cur->isEnd == true;

}

// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode * cur = root;
for(auto ch:prefix)
{
cur = cur->subNode(ch);
if(!cur)
return false;
}
return true;

}

private:
TrieNode* root;
};

// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: