Trying to add comments in for Leetcode's 1065. Index pairs of a string
Here is Input for Javascript code
Input: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"]
Here what is exepected
Here is Output expected:
[[3,7],[9,13],[10,17]]
Here is code written on which i tried adding comments for understanding the solution using Trie ,please review and let me know
if the comments looks right and if comments incorrect or missing can some add comments so as to understand the solution correctly?
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
}
Your help is appreciated
Regards
Carolyn