原题链接
    Implement a trie with insert, search, and startsWith methods.

    Example:

    1. Trie trie = new Trie();
    2. trie.insert("apple");
    3. trie.search("apple"); // returns true
    4. trie.search("app"); // returns false
    5. trie.startsWith("app"); // returns true
    6. trie.insert("app");
    7. trie.search("app"); // returns true

    Note:

    You may assume that all inputs are consist of lowercase letters a-z.
    All inputs are guaranteed to be non-empty strings.

    image.png

    1. class Trie {
    2. private:
    3. bool isEnd;
    4. Trie* next[26];
    5. public:
    6. Trie() {
    7. isEnd = false;
    8. memset(next, 0, sizeof(next));
    9. }
    10. void insert(string word) {
    11. Trie* node = this;
    12. for (char c : word) {
    13. if (node->next[c-'a'] == NULL) {
    14. node->next[c-'a'] = new Trie();
    15. }
    16. node = node->next[c-'a'];
    17. }
    18. node->isEnd = true;
    19. }
    20. bool search(string word) {
    21. Trie* node = this;
    22. for (char c : word) {
    23. node = node->next[c - 'a'];
    24. if (node == NULL) {
    25. return false;
    26. }
    27. }
    28. return node->isEnd;
    29. }
    30. bool startsWith(string prefix) {
    31. Trie* node = this;
    32. for (char c : prefix) {
    33. node = node->next[c-'a'];
    34. if (node == NULL) {
    35. return false;
    36. }
    37. }
    38. return true;
    39. }
    40. };