From ea38815e5cd7747730de18665d3b913d048056ee Mon Sep 17 00:00:00 2001 From: Eatswap Date: Fri, 17 Mar 2023 21:44:13 +0800 Subject: [PATCH] add: 230317 --- cpp/2303/230317.cpp | 69 +++++++++++++++++++++++++++++++++++++++++ cpp/2303/CMakeLists.txt | 2 +- 2 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 cpp/2303/230317.cpp diff --git a/cpp/2303/230317.cpp b/cpp/2303/230317.cpp new file mode 100644 index 0000000..d8fc387 --- /dev/null +++ b/cpp/2303/230317.cpp @@ -0,0 +1,69 @@ +#include +#include + +/** + * 208. Implement Trie (Prefix Tree) + * + * A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. + * + * Implement the Trie class: + * + * Trie() Initializes the trie object. + * void insert(String word) Inserts the string word into the trie. + * boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise. + * boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise. + */ + +struct TrieNode { + TrieNode* p[26] = {}; + bool terminate = false; +}; + +class Trie { +private: + TrieNode r; + +public: + Trie() = default; + + void insert(const std::string& word) { + TrieNode* ptr = &this->r; + for (char i : word) { + if (!ptr->p[i - 'a']) + ptr->p[i - 'a'] = new TrieNode; + ptr = ptr->p[i - 'a']; + } + ptr->terminate = true; + } + + bool search(const std::string& word) const { + const TrieNode* ptr = &this->r; + for (char i : word) { + if (!ptr->p[i - 'a']) + return false; + ptr = ptr->p[i - 'a']; + } + return ptr && ptr->terminate; + } + + bool startsWith(const std::string& prefix) const { + const TrieNode* ptr = &this->r; + for (char i : prefix) { + if (!ptr->p[i - 'a']) + return false; + ptr = ptr->p[i - 'a']; + } + return ptr; + } +}; + +int main() { + Trie trie; + trie.insert("apple"); + std::cout << trie.search("apple"); // return True + std::cout << trie.search("app"); // return False + std::cout << trie.startsWith("app"); // return True + trie.insert("app"); + std::cout << trie.search("app"); // return True + return 0; +} diff --git a/cpp/2303/CMakeLists.txt b/cpp/2303/CMakeLists.txt index 392d7dc..6994235 100644 --- a/cpp/2303/CMakeLists.txt +++ b/cpp/2303/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2303) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2303 230317-CN.cpp) +ADD_EXECUTABLE(2303 230317.cpp)