Skip to content

Commit 30f7486

Browse files
Update BoyerMoore.js
1 parent 81e72f6 commit 30f7486

1 file changed

Lines changed: 26 additions & 27 deletions

File tree

String/BoyerMoore.js

Lines changed: 26 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -11,42 +11,41 @@
1111
*
1212
**/
1313
const buildBadMatchTable = (str) => {
14-
const tableObj = {};
15-
const strLength = str.length;
14+
const tableObj = {}
15+
const strLength = str.length
1616
for (let i = 0; i < strLength - 1; i++) {
17-
tableObj[str[i]] = strLength - 1 - i;
17+
tableObj[str[i]] = strLength - 1 - i
1818
}
1919
if (tableObj[str[strLength - 1]] === undefined) {
20-
tableObj[str[strLength - 1]] = strLength;
20+
tableObj[str[strLength - 1]] = strLength
2121
}
22-
return tableObj;
22+
return tableObj
2323
}
2424

25-
2625
const boyerMoore = (str, pattern) => {
27-
let badMatchTable = buildBadMatchTable(pattern);
28-
let offset = 0;
29-
let patternLastIndex = pattern.length - 1;
30-
let scanIndex = patternLastIndex;
31-
let maxOffset = str.length - pattern.length;
26+
const badMatchTable = buildBadMatchTable(pattern)
27+
let offset = 0
28+
const patternLastIndex = pattern.length - 1
29+
let scanIndex = patternLastIndex
30+
const maxOffset = str.length - pattern.length
3231
// if the offset is bigger than maxOffset, cannot be found
3332
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-
const 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-
}
33+
scanIndex = 0
34+
while (pattern[scanIndex] === str[scanIndex + offset]) {
35+
if (scanIndex === patternLastIndex) {
36+
// found at this index
37+
return offset
38+
}
39+
scanIndex++
40+
}
41+
const badMatchString = str[offset + patternLastIndex]
42+
if (badMatchTable[badMatchString]) {
43+
// increase the offset if it exists
44+
offset += badMatchTable[badMatchString]
45+
} else {
46+
offset += 1
47+
}
4948
}
50-
return -1;
49+
return -1
5150
}
5251
export { boyerMoore }

0 commit comments

Comments
 (0)