题目:
分析:
直接用的大佬代码,
注意回顾c++类的基本知识,全局里面直接默认初始化了,用的很巧妙,还有this的使用。
代码:
class Trie {
public:
/** Initialize your data structure here. */
bool is_string = false;
Trie* next[26] = { nullptr };
Trie() {
}
/** Inserts a word into the trie. */
void insert(string word) {
Trie* root = this;
for (const auto& w : word) {
if (root->next[w - 'a'] == nullptr) root->next[w - 'a'] = new Trie();
root = root->next[w - 'a'];
}
root->is_string = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie* root = this;
for (const auto& w : word) {
if (root->next[w - 'a'] == nullptr) return 0;
root = root->next[w - 'a'];
}
return root->is_string;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie* root = this;
for (const auto& p : prefix) {
if (root->next[p - 'a'] == nullptr) return false;
root = root->next[p - 'a'];
}
return true;
}
};