https://leetcode-cn.com/problems/implement-trie-prefix-tree/

1. 题意

image.png

2. 思路

字典树的模版

3. 题解

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. class Trie {
  4. private:
  5. vector<Trie*>children;
  6. int num;
  7. bool isEnd;
  8. char ch;
  9. Trie* searchPrefix(string prefix){
  10. Trie* node = this;
  11. for(char ch : prefix) {
  12. ch = ch - 'a';
  13. if(node -> children[ch] == nullptr) {
  14. return nullptr;
  15. }
  16. node = node -> children[ch];
  17. }
  18. return node;
  19. }
  20. public:
  21. Trie() : children(26),num(0),isEnd(false){}
  22. void insert(string word) {
  23. Trie* node = this;
  24. for(char ch : word) {
  25. char temp = ch;
  26. ch -= 'a';
  27. if(node -> children[ch] == nullptr) {
  28. node -> children[ch] = new Trie;
  29. }
  30. node = node -> children[ch];
  31. node -> ch = temp;
  32. }
  33. node -> num = (node -> num) ++;
  34. node -> isEnd = true;
  35. }
  36. bool search(string word) {
  37. Trie* trie = this -> searchPrefix(word);
  38. return trie == nullptr ? false : trie -> isEnd;
  39. }
  40. bool startsWith(string prefix) {
  41. Trie* trie = this -> searchPrefix(prefix);
  42. return trie == nullptr ? false : true;
  43. }
  44. };
  45. int main()
  46. {
  47. return 0;
  48. }