문제
https://leetcode.com/problems/implement-trie-prefix-tree/
걸린 시간
-
풀이
C++
class Trie {
public:
Trie* children[26];
bool terminal;
/* char to int */
int toNumber(char ch) { return ch-'a'; }
/** Initialize your data structure here. */
Trie() {
terminal = false;
memset(children, 0, sizeof(children));
}
/** Inserts a word into the trie. */
void insert(string word) {
if(word[0] == 0) terminal = true;
else{
int next = toNumber(word[0]);
if(children[next] == NULL)
children[next] = new Trie();
children[next]->insert(word.c_str()+1);
}
}
/** Returns if the word is in the trie. */
bool search(string word) {
if(word[0] == 0) return this->terminal;
int next = toNumber(word[0]);
if(children[next] == NULL) return false;
return children[next]->search(word.c_str()+1);
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
if(prefix[0] == 0) return true;
int next = toNumber(prefix[0]);
if(children[next] == NULL) return false;
return children[next]->startsWith(prefix.c_str()+1);
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
기본적인 트라이 자료구조 구현 문제.
'LeetCode' 카테고리의 다른 글
LeetCode 147. Insertion Sort List (0) | 2021.02.25 |
---|---|
LeetCode 56. Merge Intervals (0) | 2021.02.24 |
LeetCode 297. Serialize and Deserialize Binary Tree (0) | 2021.02.08 |
LeetCode 105. Construct Binary Tree from Preorder and Inorder Traversal (0) | 2021.02.07 |
LeetCode 1038. Binary Search Tree to Greater Sum Tree (0) | 2021.02.06 |
댓글