Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();
trie.insert(“apple”);
trie.search(“apple”); // returns true
trie.search(“app”); // returns false
trie.startsWith(“app”); // returns true
trie.insert(“app”);
trie.search(“app”); // returns true
實現一個簡單的鍵樹
struct TrieNode{
bool isWord;
TrieNode* next[26];
TrieNode() :isWord(false){ memset(next, 0, sizeof(next)); }
};
class Trie {
public:
TrieNode* root;
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode* cur = root;
for (char ch : word){
TrieNode* node = cur->next[ch - 'a'];
if (node == NULL){
cur->next[ch - 'a'] = new TrieNode();
}
cur = cur->next[ch - 'a'];
}
if (!cur->isWord) cur->isWord = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode* cur = root;
for (auto ch: word)
{
TrieNode* node = cur->next[ch - 'a'];
if (!node) return false;
cur = cur->next[ch - 'a'];
}
return cur->isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode* cur = root;
for (auto ch : prefix)
{
TrieNode* node = cur->next[ch - 'a'];
if (!node) return false;
cur = cur->next[ch - 'a'];
}
return true;
}
};
summary
- 記住此鍵樹模板