admin管理员组文章数量:1636997
题目链接: https://leetcode/problems/implement-trie-prefix-tree/
Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
思路: 字典树的原理从每一个结点可以往下生长26个结点, 代表从一个字符下一个字符的情况, 所以字典树的每一个树的子树数量将不再是二叉树的左右两个结点, 而是26子树. 另外我们需要在每一个结点上有另外一个标记, 代表到当前结点的路径是否构成一个单词. 这样当很多的单词共享一些前缀和路径的时候, 我们可以知道到哪里是一个单词.
这题没有正则匹配, 所以比较简单一些.
代码比较容易理解, 如下:
class TrieNode {
public:
// Initialize your data structure here.
TrieNode():child(vector<TrieNode*>(26, NULL)), isWord(false) {
}
vector<TrieNode*> child;
bool isWord;
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
TrieNode* tem = root;
for(auto ch: word)
{
if(tem->child[ch-'a'] == NULL)
tem->child[ch-'a'] = new TrieNode();
tem = tem->child[ch-'a'];
}
tem->isWord = true;
}
// Returns if the word is in the trie.
bool search(string word) {
TrieNode* tem = root;
for(auto ch: word)
{
if(tem->child[ch-'a'] == NULL)
return false;
tem = tem->child[ch-'a'];
}
return tem->isWord;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode* tem = root;
for(auto ch: prefix)
{
if(tem->child[ch-'a'] == NULL)
return false;
tem = tem->child[ch-'a'];
}
return true;
}
private:
TrieNode* root;
};
// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");
本文标签: 报告implementLeetCodetreeprefix
版权声明:本文标题:[leetcode] 208. Implement Trie (Prefix Tree) 解题报告 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dianzi/1729235415a1191934.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论