JSFiddle - React, Tailwind, and code Playground

by Krishna Ananthi

JavaScript

var TrieNode = function(){
    this.children = {};
    this.endOfWord = true;
}

var WordDictionary = function() {
    this.root = new TrieNode();
};

/** 
 * @param {string} word
 * @return {void}
 */
WordDictionary.prototype.addWord = function(word) {
    let cur = this.root;
    for(let c of word){
        if(!cur.children[c]) 
            cur.children[c]= new TrieNode();
        cur = cur.children[c];
    }
    cur.endOfWord = true;
};

/** 
 * @param {string} word
 * @return {boolean}
 */
WordDictionary.prototype.search = function(word) {
    const dfs = (word,j,root) => {
        let cur = root;
        for(let i=j;i<word.length;i++){
            const c = word[i];
            if(c==='.'){
                for(let child in cur.children){
                    if(child && dfs(word, i+1, child))
                        return true;
                }
            }else{
                console.log(cur.children)
                if(!cur?.children[c]){
                    return false;
                }
                cur=cur.children[c];
            }
        } 
        return cur.endOfWord;
    }
    dfs(word,0,this.root)
};

/** 
 * Your WordDictionary object will be instantiated and called as such:
 * var obj = new WordDictionary()
 * obj.addWord(word)
 * var param_2 = obj.search(word)
 */


let w = new WordDictionary();
w.addWord("apple");
console.log(w.search(".p"));