diff --git a/10 October LeetCode Challenge 2021/08_trie.cpp b/10 October LeetCode Challenge 2021/08_trie.cpp new file mode 100644 index 0000000..3f1fd63 --- /dev/null +++ b/10 October LeetCode Challenge 2021/08_trie.cpp @@ -0,0 +1,36 @@ +class Trie { +public: + Trie* children[26] = {}; + bool isWord = false; + + void insert(string word) { + Trie* cur = this; + for (char c : word) { + c -= 'a'; + if (cur->children[c] == nullptr) + cur->children[c] = new Trie(); + cur = cur->children[c]; + } + cur->isWord = true; + } + + bool search(string word) { + Trie* cur = this; + for (char c : word) { + c -= 'a'; + if (cur->children[c] == nullptr) return false; + cur = cur->children[c]; + } + return cur->isWord; + } + + bool startsWith(string prefix) { + Trie* cur = this; + for (char c : prefix) { + c -= 'a'; + if (cur->children[c] == nullptr) return false; + cur = cur->children[c]; + } + return true; + } +};