add: 230317

This commit is contained in:
Eatswap 2023-03-17 21:44:13 +08:00
parent cb6cd0b214
commit ea38815e5c
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 70 additions and 1 deletions

69
cpp/2303/230317.cpp Normal file
View File

@ -0,0 +1,69 @@
#include <string>
#include <iostream>
/**
* 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;
}

View File

@ -3,4 +3,4 @@ PROJECT(2303)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2303 230317-CN.cpp) ADD_EXECUTABLE(2303 230317.cpp)