Intentando agregar comentarios para el 1065 de Leetcode. 1065. Index pairs of a string
Aquí está la entrada para el código Javascript
Input: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"] Here what is exepectedAquí está la salida esperada:
[[3,7],[9,13],[10,17]] Aquí hay un código escrito en el que intenté agregar comentarios para comprender la solución usando Trie , revíselo y hágamelo saber
si los comentarios parecen correctos y si los comentarios son incorrectos o faltan, ¿algunos pueden agregar comentarios para comprender la solución correctamente?
class Trie{ constructor(){ this.child = {} this.isWord = false this.word = '' } } // build the trie first var indexPairs = function(text, words) { const trie = buildTrie(words) const res = [] // this is basically a nested for loop to check // since each letter in text could be a potential beginning // of a valid word from given list: // ex: text = ababa: we want check: // a->end // b->end // a->end // b->end // ... for(let i=0; i<text.length;i++){ let root = trie.child[text[i]] if(!root) continue let sub = [i] let j = i while(root){ if(root.isWord){ sub.push(j) } if(sub.length == 2) { res.push(sub.slice()) sub.pop() } root = root.child[text[++j]] } } return res }; // when insert, dont forget to pass trie as a pointer to traverse down function buildTrie(words, root = new Trie()){ const og = root for(let w of words){ for(let s of w){ if(!root.child[s]) root.child[s] = new Trie() root = root.child[s] } root.isWord = true root.word = w root = og } return og }Tu ayuda es apreciada
Saludos
Carolina