You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
class TrieNode{
public:
TrieNode *child[26];
bool isWord;
TrieNode():isWord(false){
for (int i = 0; i < 26; i++) child[i] = nullptr;
}
};
class Trie {
public:
/** Initialize your data structure here. */
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 val = word[i] - 'a';
if(!p->child[val]) p->child[val] = new TrieNode();
p = p->child[val];
}
p->isWord = 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 val = word[i] - 'a';
if(!p->child[val]) return false;
p = p->child[val];
}
return p->isWord;
}
/** 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 val = prefix[i] - 'a';
if(!p->child[val]) return false;
p = p->child[val];
}
return true;
}
private:
TrieNode *root;
};
The text was updated successfully, but these errors were encountered:
题目描述:
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
说明:
解题思路:字典树的一些基本概念和操作的理解。网上扒一些。
Trie树的基本性质:
Trie树的核心思想是空间换时间,利用字符串的公共前缀来减少无谓的字符串比较以达到提高查询效率的目的。
优点
插入和查询的效率很高,都为O(m),其中 m是待插入/查询的字符串的长度。
缺点
当 hash 函数很好时,Trie树的查找效率会低于哈希搜索。
空间消耗比较大。
C++解题:
The text was updated successfully, but these errors were encountered: