跳至主要内容

208. Implement Trie (Prefix Tree)

· 閱讀時間約 1 分鐘
class TrieNode {
public:
TrieNode* child[26];
bool isWord = false;
TrieNode()
{
for (int i = 0; i < 26; ++i)
{
child[i] = nullptr;
}
}
};

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

void insert(string word)
{
TrieNode* node = root;
for (auto w : word)
{
if (!node->child[w - 'a'])
{
node->child[w - 'a'] = new TrieNode();
}
node = node->child[w - 'a'];
}
node->isWord = true;
}

bool search(string word)
{
TrieNode* node = root;
for (auto w : word)
{
if (!node->child[w - 'a']) return false;
node = node->child[w - 'a'];
}
return node->isWord;
}

bool startsWith(string prefix)
{
TrieNode* node = root;
for (auto p : prefix)
{
if (!node->child[p - 'a']) return false;
node = node->child[p - 'a'];
}
return true;
}
};

/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
  • T: $O(N)$
  • S: $O(N)$