您的位置:首页 > 其它

[LeetCode] Implement Trie (Prefix Tree)

2015-08-17 21:24 429 查看
You need to understand what a Trie is before writing the code :-) This link has a nice solution, whose code is rewritten below.

class TrieNode {
public:
bool isWord;
TrieNode* children[26];
// Initialize your data structure here.
TrieNode() : isWord(false) {
memset(children, NULL, sizeof(TrieNode*) * 26);
}
};

class Trie {
public:
Trie() {
root = new TrieNode();
}

// Inserts a word into the trie.
void insert(string word) {
TrieNode* run = root;
for (char c : word) {
if (!(run -> children[c - 'a']))
run -> children[c - 'a'] = new TrieNode();
run = run -> children[c - 'a'];
}
run -> isWord = true;
}

// Returns if the word is in the trie.
bool search(string word) {
TrieNode* p = query(word);
return p && p -> isWord;
}

// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
return query(prefix);
}

private:
TrieNode* root;
TrieNode* query(string& s) {
TrieNode* run = root;
for (char c : s) {
if (!(run -> children[c - 'a'])) return NULL;
run = run -> children[c - 'a'];
}
return run;
}
};

// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: