CS
[์๋ฃ๊ตฌ์กฐ] ํธ๋ผ์ด (Trie)
moaoh
2024. 11. 8. 02:10
ํธ๋ผ์ด (Trie) ๋?
- ๋ฌธ์์ด์ ์ ์ฅํ๊ณ , ํจ์จ์ ์ผ๋ก ํ์ํ๊ธฐ ์ํ ํธ๋ฆฌ ํํ์ ์๋ฃ๊ตฌ์กฐ
- tree ํํ์ ์๋ฃ๊ตฌ์กฐ
- ์ ๋ณด ๊ฒ์ ๊ฐ์ ๋ถ์ผ์์ ํ์ฉ๋๋ค.
- ์์ ๊ฐ์ ๊ทธ๋ฆผ์ฒ๋ผ ๋น ๋ฅด๊ฒ ๋จ์ด๋ฅผ ์ฐพ๋ ๊ฒ์ ํจ์จ์ ์ผ๋ก ๋์ํ ์ ์๋ค.
์ฅ๋จ์
์ฅ์
- ๋ฌธ์์ด ๊ฒ์์ ํจ์จ์ ์ด๋ฉฐ, ์ ๋์ฌ ๊ฒ์์ O(m) ์๊ฐ์ ์ํ ๊ฐ๋ฅ (m์ ๋ฌธ์์ด ๊ธธ์ด).
- ์๋ ์์ฑ ๊ธฐ๋ฅ ๊ตฌํ์ ์ ์ฉ.
๋จ์
- ๋ง์ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์ฌ์ฉํ๋ฉฐ, ์์ ๋ ธ๋๊ฐ ๋ง์์ง์๋ก ์ฑ๋ฅ์ด ์ ํ๋ ์ ์์.
๊ตฌํ
class TrieNode๋ฅผ ์ฌ์ฉํ ๊ตฌํ
#include <iostream>
#include <string>
#include <vector>
class TrieNode
{
private:
public:
TrieNode *child[26];
bool wordEnd;
TrieNode() {
wordEnd = false;
for(int i = 0; i < 26; i++) {
child[i] = NULL;
}
}
~TrieNode() {};
};
// trie์ ๋ฐ์ดํฐ ์ฝ์
void insertKey(TrieNode* root, const std::string& key) {
TrieNode* curr = root;
// root๋ฅผ ๊ณ์ ๋ณ๊ฒฝํ๋ฉด์ ๋ฐ์ดํฐ ์ถ๊ฐ ( ex: abc : a->b->c )
for (char c : key) {
if (curr->child[c - 'a'] == nullptr) {
TrieNode* newNode = new TrieNode();
curr->child[c - 'a'] = newNode;
}
curr = curr->child[c - 'a'];
}
curr->wordEnd = true;
}
// trie์ ๋ฐ์ดํฐ ๊ฒ์
bool searchKey(TrieNode* root, const std::string& key) {
TrieNode* curr = root;
for (char c: key) {
if (curr->child[c - 'a'] == nullptr)
return false;
curr = curr->child[c - 'a'];
}
return curr->wordEnd;
}
int main() {
TrieNode* root = new TrieNode();
std::vector<std::string> arr = {"abc", "abd", "abe", "abf"};
for (const std::string& s : arr) {
insertKey(root, s);
}
std::vector<std::string> searchKeys = {"abc", "abd", "abe", "abf", "abg", "abh"};
for (std::string& s : searchKeys) {
std::cout << "Key : " << s << "\n";
if (searchKey(root, s))
std::cout << "Present" << "\n";
else
std::cout << "Not Present" << "\n";
}
return 0;
}
- ์ํ๋ ๋ฌธ์๊ฐ TrieNode์์ ์๋์ง ์๊ฐ ๋ณต์ก๋: O(๋จ์ด ์ * maxLengthOfWord), ๋ณด์กฐ ๊ณต๊ฐ: O(๋จ์ด ์ * maxLengthOfWord) ์ผ๋ก ๋น ๋ฅด๊ฒ ์ฐพ๋๊ฒ์ด ๊ฐ๋ฅํ๋ค.