Created
June 28, 2023 11:54
-
-
Save cjnghn/c97818229d00dd182e5e08d1bf4d5c8d to your computer and use it in GitHub Desktop.
trie.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TrieNode { | |
public: | |
bool is_word; | |
TrieNode* children[26]; | |
TrieNode() { | |
is_word = false; | |
for (auto& child : children) | |
child = nullptr; | |
} | |
}; | |
class Trie { | |
private: | |
TrieNode* root; | |
public: | |
Trie() { | |
root = new TrieNode(); | |
} | |
void insert(string word) { | |
TrieNode* node = root; | |
int k = 0; | |
for (char c : word) { | |
k = c - 'a'; | |
if (node->children[k] == nullptr) { | |
node->children[k] = new TrieNode(); | |
} | |
node = node->children[k]; | |
} | |
node->is_word = true; | |
} | |
bool search(string word, bool prefix=false) { | |
TrieNode* node = root; | |
int k = 0; | |
for (char c : word) { | |
k = c - 'a'; | |
node = node->children[k]; | |
if (node == nullptr) { | |
return false; | |
} | |
} | |
return prefix ? true : node->is_word; | |
} | |
bool startsWith(string prefix) { | |
return search(prefix, true); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment