Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
字典树
class Trie {
public:
class node {
public:
node* next[26];
int end;
node() {
for (int i = 0; i < 26; ++i) {
next[i] = nullptr;
}
end = 0;
}
};
/** Initialize your data structure here. */
node* root;
Trie() {
root = new node();
}
/** Inserts a word into the trie. */
void insert(string word) {
if (word.size() == 0) return ;
node* p = root;
for (int i = 0; i < word.size(); ++i) {
int x = word[i] - 'a';
if (p->next[x] == nullptr) {
p->next[x] = new node();
p = p->next[x];
} else {
p = p->next[x];
}
}
p->end = 1;
}
/** Returns if the word is in the trie. */
bool search(string word) {
node* p = root;
for (int i = 0; i < word.size(); ++i) {
int x = word[i] - 'a';
if (p->next[x] != nullptr) {
p = p->next[x];
} else {
return false;
}
}
if (p->end == 1) return true;
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
node* p = root;
for (int i = 0; i < prefix.size(); ++i) {
int x = prefix[i] - 'a';
if (p->next[x] != nullptr) {
p = p->next[x];
} else {
return false;
}
}
return true;
}
};
/**
* 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);
*/