题目
LeetCode - 208. Implement Trie (Prefix Tree)
题目链接
https://leetcode.com/problems/implement-trie-prefix-tree/
参考博客
解题思路
解题源码
class Trie {
public:
/** Initialize your data structure here. */
set<string> s;
Trie() {
}
/** Inserts a word into the trie. */
void insert(string word) {
s.insert(word);
}
/** Returns if the word is in the trie. */
bool search(string word) {
return s.count(word) == 1;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
for (auto it : s){
int pos = it.find(prefix);
if (pos == 0) return true;
}
return false;
}
};
/**
* 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);
*/