Simple JavaScript Solution


  • 0
    D
    /**
     * Initialize your data structure here.
     */
    var MagicDictionary = function() {
        this.table = {}
    };
    
    /**
     * Build a dictionary through a list of words 
     * @param {string[]} dict
     * @return {void}
     */
    MagicDictionary.prototype.buildDict = function(dict) {
        for (let word of dict) {
            this.table[word.length] = (this.table[word.length] || []).concat(word)
        }
    };
    
    /**
     * Returns if there is any word in the trie that equals to the given word after modifying exactly one character 
     * @param {string} word
     * @return {boolean}
     */
    MagicDictionary.prototype.search = function(word) {
        return !!this.table[word.length] && this.table[word.length].some((w) => {
            let isModified = false
    
            for (let i = 0; i < word.length; ++i) {
                if (word[i] !== w[i]) {
                    if (isModified) {
                        return false
                    } else {
                        isModified = true
                    }
                }
            }
            return isModified
        })
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.