208. 实现 Trie (前缀树)

image.png

使用静态链表实现的前缀树在leetcode上空间和时间都用的比较多,因为不太方便将大数组初始化

  1. class Trie {
  2. public:
  3. Trie() {
  4. const int N = 100010;
  5. son = vector<vector<int>>(N, vector<int>(26, 0));
  6. cnt = vector<int>(N, 0);
  7. }
  8. void insert(string word) {
  9. int cur = 0;
  10. for (auto ch : word) {
  11. ch -= 'a';
  12. if (!son[cur][ch]) son[cur][ch] = ++idx;
  13. cur = son[cur][ch];
  14. }
  15. cnt[cur]++;
  16. }
  17. bool search(string word) {
  18. int cur = 0;
  19. for (auto ch : word) {
  20. ch -= 'a';
  21. if (!son[cur][ch]) return false;
  22. cur = son[cur][ch];
  23. }
  24. return cnt[cur];
  25. }
  26. bool startsWith(string prefix) {
  27. int cur = 0;
  28. for (auto ch : prefix) {
  29. ch -= 'a';
  30. if (!son[cur][ch]) return false;
  31. cur = son[cur][ch];
  32. }
  33. return true;
  34. }
  35. vector<vector<int>> son;
  36. vector<int> cnt;
  37. int idx = 0;
  38. };
  39. /**
  40. * Your Trie object will be instantiated and called as such:
  41. * Trie* obj = new Trie();
  42. * obj->insert(word);
  43. * bool param_2 = obj->search(word);
  44. * bool param_3 = obj->startsWith(prefix);
  45. */