Skip to content

Commit ab956d2

Browse files
authored
Update 3008-find-beautiful-indices-in-the-given-array-ii.js
1 parent 4399d7f commit ab956d2

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

3008-find-beautiful-indices-in-the-given-array-ii.js

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,85 @@
1+
/**
2+
* @param {string} s
3+
* @param {string} a
4+
* @param {string} b
5+
* @param {number} k
6+
* @return {number[]}
7+
*/
8+
var beautifulIndices = function (s, a, b, k) {
9+
const is = kmp(s, a)
10+
if (is.length === 0) return []
11+
12+
const js = kmp(s, b)
13+
if (js.length === 0) return []
14+
15+
const answer = []
16+
let p = 0
17+
let q = 0
18+
19+
while (p < is.length && q < js.length) {
20+
const distance = Math.abs(is[p] - js[q])
21+
22+
if (distance <= k) {
23+
answer.push(is[p])
24+
p++
25+
} else if (is[p] < js[q]) {
26+
p++
27+
} else {
28+
q++
29+
}
30+
}
31+
32+
return answer
33+
}
34+
35+
function kmp(str1, str2) {
36+
const pattern = buildPattern(str2)
37+
38+
const answer = []
39+
let i = 0
40+
let j = 0
41+
42+
while (i < str1.length) {
43+
if (str1[i] === str2[j]) {
44+
i++
45+
j++
46+
47+
if (j === str2.length) {
48+
answer.push(i - str2.length)
49+
j = pattern[j - 1] + 1
50+
}
51+
} else if (j > 0) {
52+
j = pattern[j - 1] + 1
53+
} else {
54+
i++
55+
}
56+
}
57+
58+
return answer
59+
}
60+
61+
function buildPattern(str) {
62+
const pattern = new Array(str.length).fill(-1)
63+
let i = 1
64+
let j = 0
65+
66+
while (i < str.length) {
67+
if (str[i] === str[j]) {
68+
pattern[i] = j
69+
i++
70+
j++
71+
} else if (j > 0) {
72+
j = pattern[j - 1] + 1
73+
} else {
74+
i++
75+
}
76+
}
77+
78+
return pattern
79+
}
80+
81+
// another
82+
183
/**
284
* @param {string} s
385
* @param {string} a

0 commit comments

Comments
 (0)