Skip to content

Commit 8111a43

Browse files
Update and rename boyerMoore.js to BoyerMoore.js
and fix code style.
1 parent e7cb578 commit 8111a43

File tree

2 files changed

+58
-58
lines changed

2 files changed

+58
-58
lines changed

String/BoyerMoore.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*
2+
*
3+
*
4+
*Implementation of the Boyer-Moore String Search Algo.
5+
*The Boyer–Moore string search algorithm allows linear time in
6+
* search by skipping
7+
* indices when searching inside a string for a pattern.
8+
*
9+
*
10+
*
11+
*
12+
**/
13+
const buildBadMatchTable = (str) => {
14+
let tableObj = {};
15+
let strLength = str.length;
16+
for (var i = 0; i < strLength - 1; i++) {
17+
tableObj[str[i]] = strLength - 1 - i;
18+
}
19+
if (tableObj[str[strLength-1]] == undefined) {
20+
tableObj[str[strLength-1]] = strLength;
21+
}
22+
return tableObj;
23+
}
24+
25+
26+
let boyerMoore = (str, pattern)=> {
27+
var badMatchTable = buildBadMatchTable(pattern),
28+
offset = 0,
29+
patternLastIndex = pattern.length - 1,
30+
scanIndex = patternLastIndex,
31+
maxOffset = str.length - pattern.length;
32+
// if the offset is bigger than maxOffset, cannot be found
33+
while (offset <= maxOffset) {
34+
scanIndex = 0;
35+
while (pattern[scanIndex] == str[scanIndex + offset]) {
36+
if (scanIndex == patternLastIndex) {
37+
// found at this index
38+
return offset;
39+
}
40+
scanIndex++;
41+
}
42+
var badMatchString = str[offset + patternLastIndex];
43+
if (badMatchTable[badMatchString]) {
44+
// increase the offset if it exists
45+
offset += badMatchTable[badMatchString]
46+
} else {
47+
offset += 1;
48+
}
49+
}
50+
return -1;
51+
}
52+
export {boyerMoore}
53+
54+
55+
56+
57+
58+

String/boyerMoore.js

Lines changed: 0 additions & 58 deletions
This file was deleted.

0 commit comments

Comments
 (0)