您的位置:首页 > 其它

LeetCode "Implement Trie (Prefix Tree)"

2015-05-13 13:28 232 查看
Implementation problem.

class TrieNode {
public:
// Initialize your data structure here.
TrieNode() {
c = 0;
bIsLast = false;
}
TrieNode(char vc) {
c = vc;
bIsLast = false;
}
public:
char c;
bool bIsLast;
map<char, TrieNode> childMap;
};

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

~Trie()
{
if (root)
delete root;
}

// Inserts a word into the trie.
void insert(string s) {
TrieNode *r = root;
for (int i = 0; i < s.length(); i++)
{
if (r->childMap.find(s[i]) == r->childMap.end())
{
r->childMap.insert(make_pair(s[i], TrieNode(s[i])));
}

r = &(r->childMap[s[i]]);
}
r->bIsLast = true;
}

// Returns if the word is in the trie.
bool search(string key) {
TrieNode *r = root;
for (int i = 0; i < key.length(); i++)
{
if (r->childMap.find(key[i]) == r->childMap.end())
{
return false;
}

r = &(r->childMap[key[i]]);
}

return r->bIsLast;
}

// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode *r = root;
for (int i = 0; i < prefix.length(); i++)
{
if (r->childMap.find(prefix[i]) == r->childMap.end())
{
return false;
}

r = &(r->childMap[prefix[i]]);
}
return true;
}

private:
TrieNode* root;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: