Skip to content

Commit 53415dc

Browse files
authored
Create 1065-index-pairs-of-a-string.js
1 parent 5c385e2 commit 53415dc

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

1065-index-pairs-of-a-string.js

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* @param {string} text
3+
* @param {string[]} words
4+
* @return {number[][]}
5+
*/
6+
const indexPairs = function(text, words) {
7+
const res = [], trie = buildTrie(words)
8+
const n = text.length
9+
for(let i = 0; i < n; i++) {
10+
let node = trie
11+
for(let j = i; j < n; j++) {
12+
if(node.children[text[j]] == null) break
13+
node = node.children[text[j]]
14+
if(node.isWord) res.push([i, j])
15+
}
16+
}
17+
18+
return res
19+
};
20+
21+
function buildTrie(words) {
22+
const root = new Trie()
23+
24+
for(let word of words) {
25+
let node = root
26+
for(let c of word) {
27+
if(node.children[c] == null) node.children[c] = new Trie()
28+
node = node.children[c]
29+
}
30+
node.isWord = true
31+
}
32+
33+
return root
34+
}
35+
36+
class Trie {
37+
constructor() {
38+
this.children = {}
39+
this.isWord = false
40+
}
41+
}

0 commit comments

Comments
 (0)