반응형
https://leetcode.com/problems/implement-trie-prefix-tree/
Implement Trie (Prefix Tree) - LeetCode
Can you solve this real interview question? Implement Trie (Prefix Tree) - A trie [https://en.wikipedia.org/wiki/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
leetcode.com
트라이 구현 문제였습니다.
class Trie {
public:
Trie() {
for(int i=0;i<26; i++) nextTrie[i] = NULL;
}
void insert(string word) {
insertInternal(word, 0);
}
bool search(string word) {
return searchInternal(word, 0);
}
bool startsWith(string prefix) {
return startsWithInternal(prefix, 0);
}
private:
bool flag = false;
Trie* nextTrie[26];
void insertInternal(string& word, int wordIdx) {
if(isLast(word, wordIdx)) {
flag = true;
return;
}
int nxtIdx = word[wordIdx] - 'a';
if(nextTrie[nxtIdx] == NULL) nextTrie[nxtIdx] = new Trie();
nextTrie[nxtIdx]->insertInternal(word, wordIdx + 1);
}
bool searchInternal(string& word, int wordIdx) {
if(isLast(word, wordIdx)) return flag;
int nxtIdx = word[wordIdx] - 'a';
if(nextTrie[nxtIdx] == NULL) return false;
return nextTrie[nxtIdx]->searchInternal(word, wordIdx+1);
}
bool startsWithInternal(string& word, int wordIdx) {
if(isLast(word, wordIdx)) return true;
int nxtIdx = word[wordIdx] - 'a';
if(nextTrie[nxtIdx] == NULL) return false;
return nextTrie[nxtIdx]->startsWithInternal(word, wordIdx + 1);
}
bool isLast(string& word, int wordIdx) {
return word.size() == wordIdx;
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 211. Design Add and Search Words Data Structure (0) | 2023.03.19 |
---|---|
LeetCode 1472. Design Browser History (0) | 2023.03.18 |
LeetCode 958. Check Completeness of a Binary Tree (0) | 2023.03.15 |
LeetCode 129. Sum Root to Leaf Numbers (0) | 2023.03.15 |
LeetCode 101. Symmetric Tree (0) | 2023.03.13 |