【LeetCode 208】Implement Trie (Prefix Tree)

时间:2024-01-12 11:54:14

Implement a trie with insertsearch, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

思路:

构建一个简单的字典树,要求实现插入、查找、查找前缀三个操作。这里使用map实现对子树的构建(一方面方便查找,另一方面是懒 - -!),但是效率并不是太高,LeetCode上提交后跑了147ms,不是很理想,不过不影响对字典树这种树形结构的理解。

 class TrieNode {
public:
// Initialize your data structure here.
TrieNode(char c):ch(c), isEnd(false){} map<char, TrieNode *> childNode; char ch;
bool isEnd;
}; class Trie {
public:
Trie() {
root = new TrieNode('#');
} // Inserts a word into the trie.
void insert(string s) { TrieNode *t = root; //从root遍历待插入字符串,若c存在则继续向下遍历,反之则新建一个分支
for(int i = ; i < s.length(); i++)
{
char c = s[i]; map<char, TrieNode*>::iterator it = t->childNode.find(c);
if(it == t->childNode.end())
{
TrieNode *newNode = new TrieNode(c);
t->childNode.insert(make_pair(c, newNode));
t = newNode;
}
else
{
t = t->childNode[c];
}
}
t->isEnd = true;
} // Returns if the word is in the trie.
bool search(string key) {
TrieNode *s = root; //从root遍历待查找字符串,若c存在则向下遍历,反之则不存在
for(int i = ; i < key.length(); i++)
{
char c = key[i]; map<char, TrieNode*>::iterator it = s->childNode.find(c);
if(it == s->childNode.end())
return false;
else
s = s->childNode[c];
}
//返回最后一个结点的状态,判断是否为一个word
return s->isEnd;
} // Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode *s = root; //与search一致
for(int i = ; i < prefix.length(); i++)
{
char c = prefix[i]; map<char, TrieNode*>::iterator it = s->childNode.find(c); if(it == s->childNode.end())
return false;
else
s = s->childNode[c];
}
//只要找到即返回true
return true;
} private:
TrieNode* root;
};