LeetCode - Implement Trie (Prefix Tree) - C++

preview_player
Показать описание
Let's discuss ⬇️
Рекомендации по теме
Комментарии
Автор

struct TrieNode {
TrieNode *children[26];
bool isWord;

TrieNode() {
for (auto &c : children) {
c = nullptr;
}
isWord = false;
}
};

class Trie {
private:
TrieNode *root;

void clear(TrieNode *tn) {
for (int i = 0; i < 26; i++) {
if (tn->children[i]) {
clear(tn->children[i]);
}
}
delete tn;
}

TrieNode *find(string &s) {
// TC: O(n), n = length of word
TrieNode *tn = root;
for (auto &c : s) {
if (!tn->children[c - 'a']) {
return nullptr;
}
tn = tn->children[c - 'a'];
}
return tn;
}

public:
Trie() {
// SC: O(M*N) M = average length of word, N = number of words
root = new TrieNode();
}

~Trie() {
clear(root);
}

void insert(string word) {
// TC: O(n), n = length of word
TrieNode *tn = root;
for (auto &c : word) {
if (!tn->children[c - 'a']) {
tn->children[c - 'a'] = new TrieNode();
}
tn = tn->children[c - 'a'];
}
tn->isWord = true;
}

bool search(string word) {
TrieNode *end = find(word);
if (end && end->isWord) {
return true;
}
return false;
}

bool startsWith(string prefix) {
if (find(prefix)) { return true; }
return false;
}
};

lansicus
Автор

I really liked your implementation, most people ignored the destructor, and I feel like your code and syntax is quite elegant as well. Bravo!

pablobear
join shbcf.ru