208. 实现 Trie (前缀树)

使用静态链表实现的前缀树在leetcode上空间和时间都用的比较多,因为不太方便将大数组初始化
class Trie {public:Trie() {const int N = 100010;son = vector<vector<int>>(N, vector<int>(26, 0));cnt = vector<int>(N, 0);}void insert(string word) {int cur = 0;for (auto ch : word) {ch -= 'a';if (!son[cur][ch]) son[cur][ch] = ++idx;cur = son[cur][ch];}cnt[cur]++;}bool search(string word) {int cur = 0;for (auto ch : word) {ch -= 'a';if (!son[cur][ch]) return false;cur = son[cur][ch];}return cnt[cur];}bool startsWith(string prefix) {int cur = 0;for (auto ch : prefix) {ch -= 'a';if (!son[cur][ch]) return false;cur = son[cur][ch];}return true;}vector<vector<int>> son;vector<int> cnt;int idx = 0;};/*** 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);*/
