您的位置:首页 > 其它

LeetCode OJ 之 Implement Trie (Prefix Tree) 实现Trie(前缀树)

2015-08-03 10:13 351 查看

题目:

Implement a trie with 
insert
search
,
and 
startsWith
 methods.

Note:

You may assume that all inputs are consist of lowercase letters 
a-z
.
实现Trie的插入,查找,前缀查找操作。
假设所有输入都是由小写字母组成。

思路:

Trie树定义:https://zh.wikipedia.org/wiki/Trie 。

Trie结点定义为:

class TrieNode
{
public:
// Initialize your data structure here.
bool isWord;
TrieNode *next[26];
TrieNode()
{
isWord = false;
for(int i = 0 ; i < 26 ; i++)
next[i] = NULL;
}
};

其中isWord表示从根结点到当前结点的路径是否为一个单词。如果p->next[0]非空表示当前结点下有字符'a'。

代码:

class TrieNode
{
public:
// Initialize your data structure here.
bool isWord;
TrieNode *next[26];
TrieNode()
{
isWord = false;
for(int i = 0 ; i < 26 ; i++)
next[i] = NULL;
}
};

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

// Inserts a word into the trie.
void insert(string word)
{
int len = word.size();
TrieNode *p = root;
for(int i = 0 ; i < len ; i++)
{
//如果不存在,则建立新结点。如果存在,则继续向下
if(p->next[word[i] - 'a'] == NULL)
p->next[word[i] - 'a'] = new TrieNode();
p = p->next[word[i] - 'a'];
}
p->isWord = true; //把最后一个结点的isWord置为true,表示从根结点到当前结点保存了一个单词
}

// Returns if the word is in the trie.
bool search(string word)
{
TrieNode *p = find(word);
return p != NULL && p->isWord; //还要判断当前结点的isWord是否为真,为真才表示是个单词。如果为假,则表示word只是已存在单词的前缀
}

// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix)
{
TrieNode *p = find(prefix);
return p != NULL; //和上面一个函数比较,这里由于查找前缀,因此不需要判断isWord
}

//查找key是否存在
TrieNode *find(string key)
{
int len = key.size();
TrieNode *p = root;
for(int i = 0 ; i < len && p != NULL ; i++)
{
p = p->next[key[i] - 'a'];
}
return p;
}
private:
TrieNode* root; //注意:根结点并不表示字符
};

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