Skip to content

Commit e7cb578

Browse files
Created boyerMoore.js
Added boyerMoore string searching algorithm
1 parent 2e63444 commit e7cb578

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
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. Fo
8+
*
9+
*
10+
*
11+
*
12+
* */
13+
let buildBadMatchTable = (str) => {
14+
var tableObj = {},
15+
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+

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy