您的位置:首页 > 其它

[LeetCode]Implement Trie (Prefix Tree)

2015-07-24 15:22 344 查看
解题思路:
字典树,每个节点应该包括 isWord(是否有单词在这个node结束) ,freq (词频统计,这里没用到),child(包含26个child)

1,insert操作:遍历word每一个字符,如果cur对应的child为空,就new一个新的TrieNode,最后isWord = true;
2,search 和 startsWith都是调用searchTree这个方法;
3,searchTree第三个参数findPrefix用于判断是 搜索全单词,还是搜索前缀
searchTree逻辑
1,如果root为空,说明call这个searchTree的那个char不存在,返回false
2,如果*ch == ‘\0’ ,查询结束,如果findPrefix为真,则返回true,否则返回isWord
3,递归。

class TrieNode {
public:
vector<TrieNode *> child;
int freq;
bool isWord;
char ch;
// Initialize your data structure here.
TrieNode():freq(0), isWord(false),
child(vector<TrieNode*>(26, nullptr)),
ch('\0'){

}
};

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

// Inserts a word into the trie.
void insert(string word) {

TrieNode* cur = root;
for (int i = 0; i < word.length(); ++i){
int ind = word[i] - 'a';
if (cur->child[ind] == NULL){
cur->child[ind] = new TrieNode();
}
cur = cur->child[ind];
}
cur->isWord = true;
}

// Returns if the word is in the trie.
bool search(string word) {
return searchTree(word.c_str(), root, false);
}

bool searchTree(const char* ch, TrieNode *root, bool findPrefix){
if (root == NULL) return false;
if (*ch == '\0') return findPrefix ? true : root->isWord;

int ind = *ch - 'a';
return searchTree(ch+1, root->child[ind], findPrefix);
}

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

private:
TrieNode* root;
};

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