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) ์œผ๋กœ ๋น ๋ฅด๊ฒŒ ์ฐพ๋Š”๊ฒƒ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

 

์ฐธ๊ณ ์ž๋ฃŒ

https://www.geeksforgeeks.org/trie-insert-and-search/