题目:
A 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 are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
Trie()
Initializes the trie object.void insert(String word)
Inserts the stringword
into the trie.boolean search(String word)
Returnstrue
if the stringword
is in the trie (i.e., was inserted before), andfalse
otherwise.boolean startsWith(String prefix)
Returnstrue
if there is a previously inserted stringword
that has the prefixprefix
, andfalse
otherwise.
Example 1:
Input ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]] Output [null, null, true, false, true, null, true] Explanation Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // return True trie.search("app"); // return False trie.startsWith("app"); // return True trie.insert("app"); trie.search("app"); // return True
Constraints:
1 <= word.length, prefix.length <= 2000
word
andprefix
consist only of lowercase English letters.- At most
3 * 104
calls in total will be made toinsert
,search
, andstartsWith
.
思路:
事现字典树,具体含义可百度。基本成员变量为一个本身类的数组,这里因为是26个字母,因此直接定义长26即可,另一个是bool来判断当前点位是不是一个确认的词。这里如果不是26个字母,可以用unordered_map。insert要注意点是如果当前点child的下一个字母是空的,就新建。search则如果在中间已经发现当前字母不在路径中,可以直接返回false,最后确认一下bool值是不是true。startWith和search差不多,区别在于只要路径对,走到那个点就行了,不用在意是不是一个完整的词,即不需要在意bool的值。
代码:
class Trie {
public:
Trie() {
}
void insert(string word) {
Trie* cur = this;
for (int i = 0; i < word.size(); i++) {
int c = word[i] - 'a';
if (!cur->child[c]) {
cur->child[c] = new Trie();
}
cur = cur->child[c];
}
cur->flag = true;
}
bool search(string word) {
Trie* cur = this;
for (int i = 0; i < word.size(); i++) {
int c = word[i] - 'a';
if (!cur->child[c])
return false;
cur = cur->child[c];
}
return cur->flag;
}
bool startsWith(string prefix) {
Trie* cur = this;
for (int i = 0; i < prefix.size(); i++) {
int c = prefix[i] - 'a';
if (!cur->child[c])
return false;
cur = cur->child[c];
}
return true;
}
private:
Trie* child[26] = {nullptr};
bool flag = 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);
*/