LeetCode OJ 之 Implement Trie (Prefix Tree) 实现Trie(前缀树)
2015-08-03 10:13
351 查看
题目:
Implement a trie withinsert,
search,
and
startsWithmethods.
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");
相关文章推荐
- JDK1.5以后各版本新特性
- 十大经典排序总结
- View的绘制过程方法
- objective-c 中随机数的用法 (3种:arc4random() 、random()、CCRANDOM_0_1() )
- Docker build and using it.
- 3. HTML DOM Attribute 对象
- java Collection源码解析
- 可动态布局的android抽屉效果
- HDU 1520 Anniversary party
- The database principal owns a schema in the database, and cannot be dropped. (.Net SqlClient Data Pr
- 南邮 OJ 1014 数据的插入与删除
- Echarts柱状图的点击事件
- jquery简单实现幻灯片的方法
- Jave学习笔记一
- 互联网人所处氛围谈:工作是一场雁过留痕的游行
- HDU 4727 The Number Off of FFF(水题)
- 算法速成(3)线性表
- 如何优雅的使用 Mac
- SQL关于日期的查询
- SSAS服务的发布