forked from loiane/javascript-datastructures-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrabin-karp.ts
39 lines (30 loc) · 1.02 KB
/
rabin-karp.ts
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
const base = 997;
const hash = (word: string) => {
let h = 0;
for (let i = 0; i < word.length; i++) {
h += word.charCodeAt(i) * Math.pow(base, word.length - i - 1);
}
return h;
};
const rabinKarp = (text: string, pattern: string) => {
if (pattern == null || pattern.length === 0) {
return 0;
}
const hashPattern = hash(pattern);
let currentSubstring = text.substring(0, pattern.length);
let hashCurrentSubstring;
for (let i = pattern.length; i <= text.length; i++) {
if (hashCurrentSubstring === undefined) {
hashCurrentSubstring = hash(currentSubstring);
} else {
hashCurrentSubstring -= currentSubstring.charCodeAt(0) * Math.pow(base, pattern.length - 1);
hashCurrentSubstring *= base;
hashCurrentSubstring += text.charCodeAt(i);
currentSubstring = currentSubstring.substring(1) + text[i];
}
if (hashPattern === hashCurrentSubstring && pattern === currentSubstring) {
return i === pattern.length ? 0 : i - pattern.length + 1;
}
}
return -1;
};