字典树
    实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。

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

    a
    |
    [b c d]
    | |——|
    [e f g] [h i k]
    插入即按单词的字符循环插入,如果当前节点已经有了当前字符,就不用新开辟一个节点。
    查找即按单词的字符循环查找节点对应的map,如果没有,即返回失败。
    map里存的是每个字母后面连接的其他所有字母

    1. class Trie {
    2. struct TrieNode {
    3. map<char, TrieNode *> child_table;//map索引为当前字母;值指向下一级node,下一级node也存放一个map表。
    4. int end; //也就是说每一个字母的下一级都会维护一个map表。
    5. TrieNode(): end(0) {};
    6. };
    7. public:
    8. /** Initialize your data structure here. */
    9. Trie() {
    10. root = new TrieNode();
    11. }
    12. /** Inserts a word into the trie. */
    13. void insert(string word) {
    14. TrieNode *cur = root;
    15. for (int i = 0; i < word.size(); i++) {
    16. if (cur->child_table.count(word[i]) == 0) {
    17. cur->child_table[word[i]] = new TrieNode();
    18. }
    19. cur = cur->child_table[word[i]];
    20. }
    21. cur->end = 1;
    22. }
    23. /** Returns if the word is in the trie. */
    24. bool search(string word) {
    25. return find(word, 1);
    26. }
    27. /** Returns if there is any word in the trie that starts with the given prefix. */
    28. bool startsWith(string prefix) {
    29. return find(prefix, 0);
    30. }
    31. private:
    32. bool find(string word, int extra_flag) { //查找即按层查找单词对应的字符。没有就返回false,有,且word查找到最后则看end标志位。
    33. TrieNode *cur = root;
    34. for (int i = 0; i < word.size(); i++) {
    35. if (cur->child_table.count(word[i]) == 0) {
    36. return false;
    37. }
    38. cur = cur->child_table[word[i]];
    39. }
    40. //找到前缀
    41. // 向下找单词
    42. //
    43. if (extra_flag) {
    44. return (cur->end) ? true : false;
    45. }else {
    46. return true;
    47. }
    48. }
    49. private:
    50. TrieNode *root;
    51. };
    1. class Trie {
    2. struct TrieNode {
    3. unorder_map<char, TrieNode*> child;
    4. int end;
    5. TrieNode():end(0){};
    6. };
    7. };