Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

208. Implement Trie (Prefix Tree) #160

Open
Tcdian opened this issue May 14, 2020 · 1 comment
Open

208. Implement Trie (Prefix Tree) #160

Tcdian opened this issue May 14, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented May 14, 2020

208. Implement Trie (Prefix Tree)

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

Example

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");   
trie.search("app");     // returns true

Note

  • 你可以假设所有的输入都是由小写字母 a-z 构成的。
  • 保证所有输入均为非空字符串。
@Tcdian Tcdian added the Trie label May 14, 2020
@Tcdian
Copy link
Owner Author

Tcdian commented May 14, 2020

Solution

  • JavaScript Solution
/**
 * Initialize your data structure here.
 */
var Trie = function() {
    this.root = new TrieNode();
};

/**
 * Inserts a word into the trie. 
 * @param {string} word
 * @return {void}
 */
Trie.prototype.insert = function(word) {
    let patrol = this.root;
    for (let i = 0; i < word.length; i++) {
        patrol.data[word[i]] = patrol.data[word[i]] || new TrieNode();
        patrol = patrol.data[word[i]];
    }
    patrol.isEnd = true;
};

/**
 * Returns if the word is in the trie. 
 * @param {string} word
 * @return {boolean}
 */
Trie.prototype.search = function(word) {
    let patrol = this.root;
    for (let i = 0; i < word.length; i++) {
        if ((patrol = patrol.data[word[i]]) === undefined) {
            return false;
        }
    }
    return patrol.isEnd;
};

/**
 * Returns if there is any word in the trie that starts with the given prefix. 
 * @param {string} prefix
 * @return {boolean}
 */
Trie.prototype.startsWith = function(prefix) {
    let patrol = this.root;
    for (let i = 0; i < prefix.length; i++) {
        if ((patrol = patrol.data[prefix[i]]) === undefined) {
            return false;
        }
    }
    return true;
};

function TrieNode() {
    this.data = Object.create(null);
    this.isEnd = false;
}

/** 
 * Your Trie object will be instantiated and called as such:
 * var obj = new Trie()
 * obj.insert(word)
 * var param_2 = obj.search(word)
 * var param_3 = obj.startsWith(prefix)
 */

@Tcdian Tcdian added the Classic label May 14, 2020
@Tcdian Tcdian removed the Classic label Jul 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant