1. 插入一个字符串
    2. 查找字符串
    3. 查找是否字符串前缀
    4. 两种查找区别在于:是否isEnd
    5. 一次建树,多次查询
    1. class Trie {
    2. private:
    3. vector<Trie *> children;
    4. bool isEnd;
    5. public:
    6. /** Initialize your data structure here. */
    7. Trie() {
    8. children.resize(26, nullptr);
    9. isEnd = false;
    10. }
    11. /** Inserts a word into the trie. */
    12. void insert(string word) {
    13. Trie *node = this;
    14. for (int i = 0; i < word.size(); i++) {
    15. int ch = word[i] - 'a';
    16. if (node->children[ch] == nullptr) {
    17. node->children[ch] = new Trie();
    18. }
    19. node = node->children[ch];
    20. }
    21. node->isEnd = true;
    22. }
    23. /** Returns if the word is in the trie. */
    24. bool search(string word) {
    25. Trie *node = this;
    26. for (int i = 0; i < word.size(); i++) {
    27. int ch = word[i] - 'a';
    28. if (node->children[ch] == nullptr) {
    29. return false;
    30. }
    31. node = node->children[ch];
    32. }
    33. return (node != nullptr && node->isEnd);
    34. }
    35. /** Returns if there is any word in the trie that starts with the given prefix. */
    36. bool startsWith(string prefix) {
    37. Trie *node = this;
    38. for (int i = 0; i < prefix.size(); i++) {
    39. int ch = prefix[i] - 'a';
    40. if (node->children[ch] == nullptr) {
    41. return false;
    42. }
    43. node = node->children[ch];
    44. }
    45. return (node != nullptr);
    46. }
    47. };
    48. /**
    49. * Your Trie object will be instantiated and called as such:
    50. * Trie* obj = new Trie();
    51. * obj->insert(word);
    52. * bool param_2 = obj->search(word);
    53. * bool param_3 = obj->startsWith(prefix);
    54. */