这道字典树就真的很简单了,一个插入、一个查找、还有一个查找前缀的,没有.的情况,所以也不需要用到递归,可以跟finaltest的1007一起理解,1007还要复杂一点。
#include <string.h>
using namespace std;
class TrieNode {
public:
// Initialize your data structure here.
TrieNode() {
end = false;
memset(child, 0, sizeof(child));
}
bool end;
TrieNode *child[26];
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
int counter = 0;
TrieNode *current = root;
while (counter != word.length()) {
if (!current->child[word[counter] - 'a']) {
current->child[word[counter] - 'a'] = new TrieNode();
}
current = current->child[word[counter] - 'a'];
if (counter == word.length() - 1) {
current->end = true;
}
counter++;
}
}
// Returns if the word is in the trie.
bool search(string word) {
int counter = 0;
TrieNode *current = root;
while (counter != word.length()) {
if (!current->child[word[counter] - 'a']) {
return false;
}
current = current->child[word[counter] - 'a'];
counter++;
}
return current->end;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
int counter = 0;
TrieNode *current = root;
while (counter != prefix.length()) {
if (!current->child[prefix[counter] - 'a']) {
return false;
}
current = current->child[prefix[counter] - 'a'];
counter++;
}
return true;
}
private:
TrieNode* root;
};
// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");
int main(int argc, const char * argv[]) {
// insert code here...
Trie trie;
trie.insert("ab");
cout << trie.search("a") << endl;
cout << trie.search("ab") << endl;
cout << trie.startsWith("a") << endl;
cout << trie.startsWith("ab") << endl;
std::cout << "Hello, World!\n";
return 0;
}
leetcode-208-Implement Trie (Prefix Tree)
最新推荐文章于 2024-03-22 00:51:13 发布