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

    • 你可以假设所有的输入都是由小写字母 a-z 构成的。
    • 保证所有输入均为非空字符串。

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

    示例:

    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
    8. 来源:力扣(LeetCode
    9. 链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree
    10. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    答案

    1. /**
    2. * Initialize your data structure here.
    3. */
    4. var Trie = function() {
    5. this.map= new Map()
    6. };
    7. /**
    8. * Inserts a word into the trie.
    9. * @param {string} word
    10. * @return {void}
    11. */
    12. Trie.prototype.insert = function(word) {
    13. if (this.map.has(word)) {
    14. return true
    15. }
    16. this.map.set(word, word)
    17. };
    18. /**
    19. * Returns if the word is in the trie.
    20. * @param {string} word
    21. * @return {boolean}
    22. */
    23. Trie.prototype.search = function(word) {
    24. return this.map.has(word)
    25. };
    26. /**
    27. * Returns if there is any word in the trie that starts with the given prefix.
    28. * @param {string} prefix
    29. * @return {boolean}
    30. */
    31. Trie.prototype.startsWith = function(prefix) {
    32. for (let [key, value] of this.map) {
    33. if (key.startsWith(prefix)) {
    34. return true
    35. }
    36. }
    37. return false
    38. };
    39. /**
    40. * Your Trie object will be instantiated and called as such:
    41. * var obj = new Trie()
    42. * obj.insert(word)
    43. * var param_2 = obj.search(word)
    44. * var param_3 = obj.startsWith(prefix)
    45. */

    感觉这个思路的难度不大,但是我的执行不知道为啥耗时这么高