您的位置:首页 > 其它

LeetCode OJ:Implement Trie (Prefix Tree)(实现一个字典树(前缀树))

2016-01-13 16:30 513 查看
Implement a trie with
insert
,
search
, and
startsWith
methods.

实现字典树,前面好像有道题做过类似的东西,代码如下:

class TrieNode {
public:
// Initialize your data structure here.
TrieNode():isLeaf(false)
{
for(auto & t : dic){
t = NULL;
}
}
TrieNode * dic[26];
bool isLeaf;
};

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

// Inserts a word into the trie.
void insert(string word) {
TrieNode * p = root;
for(int i = 0; i < word.size(); ++i){
int index = word[i] - 'a';
if(p->dic[index] == NULL)
p->dic[index] = new TrieNode();
p = p->dic[index];
}
p->isLeaf = 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 index = word[i] - 'a';
if(p->dic[index] == NULL)
return false;
p = p->dic[index];
}
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;
for(int i = 0; i < prefix.size(); ++i){
int index = prefix[i] - 'a';
if(p->dic[index] == NULL)
return false;
p = p->dic[index];
}
return true;
}

private:
TrieNode* root;
};

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