From 13fc24a5a265824fdbf68405479eb322aab98b8c Mon Sep 17 00:00:00 2001 From: Fazeel Usmani Date: Fri, 8 Oct 2021 12:05:12 +0530 Subject: [PATCH] Create 08_trie.cpp --- .../08_trie.cpp | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 10 October LeetCode Challenge 2021/08_trie.cpp 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; + } +};