LeetCode—树—Tire
Trie,又称前缀树或字典树,用于判断字符串是否存在或者是否具有某种字符串前缀。
1、实现一个 Trie
T208. Implement Trie (Prefix Tree) (Medium)
class TrieNode {
public:
TrieNode *child[26];
bool isWord;
TrieNode(): isWord(false) {
for (auto &a : child) a = nullptr;
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
void insert(string s) {
TrieNode *p = root;
for (auto &a : s) {
int i = a - 'a';
if (!p->child[i]) p->child[i] = new TrieNode();
p = p->child[i];
}
p->isWord = true;
}
bool search(string key) {
TrieNode *p = root;
for (auto &a : key) {
int i = a - 'a';
if (!p->child[i]) return false;
p = p->child[i];
}
return p->isWord;
}
bool startsWith(string prefix) {
TrieNode *p = root;
for (auto &a : prefix) {
int i = a - 'a';
if (!p->child[i]) return false;
p = p->child[i];
}
return true;
}
private:
TrieNode* root;
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
2、实现一个 Trie,用来求前缀和
T677. Map Sum Pairs (Medium)
class MapSum {
public:
/** Initialize your data structure here. */
MapSum() {}
void insert(string key, int val) {
int diff = val - m[key].first, n = key.size();
m[key].first = val;
for (int i = n - 1; i > 0; --i) {
m[key.substr(0, i)].second += diff;
}
}
int sum(string prefix) {
return m[prefix].first + m[prefix].second;
}
private:
unordered_map<string, pair<int, int>> m;
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum* obj = new MapSum();
* obj->insert(key,val);
* int param_2 = obj->sum(prefix);
*/