-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathKMP.html
More file actions
48 lines (46 loc) · 1.08 KB
/
Copy pathKMP.html
File metadata and controls
48 lines (46 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>KMP</title>
</head>
<body>
<script>
function calNext(str, len, next) {
let j = -1;
next[0] = -1;
for (let i = 1; i < len; i++) {
while (j > -1 && str[j + 1] !== str[i]) {
j = next[j]
}
if (str[i] === str[j + 1]) {
j++
}
next[i] = j
}
}
function kmp(str, pstr) {
let slen = str.length,
plen = pstr.length,
j = -1,
next = new Array(plen),
res = [];
calNext(pstr, plen, next);
for (let i = 0; i < slen; i++) {
while (j > -1 && str[i] !== pstr[j + 1]) {
j = next[j]
}
if (str[i] === pstr[j + 1]) {
j++
}
if (j === plen - 1) {
res.push(i - j);
j = -1
}
}
return res.length ? res : 0
}
console.log(kmp("bbc abcdab abcdababacde", "ababac"))
</script>
</body>
</html>