您的位置:首页 > 其它

leetcode---Implement Trie (Prefix Tree)---Trie树

2016-11-21 22:00 363 查看
Implement a trie with
insert
,
search
, and
startsWith
methods.

class TrieNode {
public:
// Initialize your data structure here.
bool isLeaf;
TrieNode *childs[26];

TrieNode() {
isLeaf = false;
memset(childs, 0, sizeof(childs));
}
};

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

// Inserts a word into the trie.
void insert(string word) {
int i = 0;
int n = word.size();
TrieNode *p = root;
while(i < n)
{
int j = word[i] - 'a';
if(p->childs[j] == NULL)
p->childs[j] = new TrieNode();
p = p->childs[j];
i++;
}
p->isLeaf = true;
}

// Returns if the word is in the trie.
bool search(string word) {
TrieNode *p = root;
int n = word.size();
if(n == 0)
return true;
int i = 0;
while(i < n)
{
int j = word[i] - 'a';
if(p->childs[j] == NULL)
return false;
p = p->childs[j];
i++;
}
return p->isLeaf;
}

// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode *p = root;
int n = prefix.size();
if(n == 0)
return true;
int i = 0;
while(i < n)
{
int j = prefix[i] - 'a';
if(p->childs[j] == NULL)
return false;
p = p->childs[j];
i++;
}
return true;
}

private:
TrieNode* root;
};

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