Skip to content

Commit 0a5c624

Browse files
committed
string : boyerMoore
1 parent 3fc78c6 commit 0a5c624

1 file changed

Lines changed: 9 additions & 6 deletions

File tree

src/string/boyerMoore.js

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
* @typedef {Object} PatternTable
44
* @property {Object[]} badCharacter badCharacter
55
* @property {number[]} goodSuffix goodSuffix
6+
* @property {number} length
67
*/
78

89
/**
@@ -23,6 +24,7 @@ function buildPattern(pattern) {
2324
// console.table(badCharacter);
2425
// console.table(goodSuffix);
2526
return {
27+
length,
2628
badCharacter,
2729
goodSuffix,
2830
};
@@ -35,8 +37,9 @@ function buildPattern(pattern) {
3537
* @param {string} dismatchChar dismatch character
3638
*/
3739
function getOffset(patternTable, dismatchIndex, badChar) {
38-
let posBadChar = patternTable.badCharacter[dismatchIndex][badChar] || -1;
39-
return Math.max(dismatchIndex - posBadChar, patternTable.goodSuffix[dismatchIndex]);
40+
let posBadChar = patternTable.badCharacter[dismatchIndex][badChar] === undefined ? -1 : patternTable.badCharacter[dismatchIndex][badChar];
41+
return dismatchIndex - posBadChar;
42+
// return Math.max(dismatchIndex - posBadChar, patternTable.goodSuffix[dismatchIndex]);
4043
}
4144

4245
/**
@@ -50,8 +53,8 @@ function boyerMoore(text, pattern) {
5053
return 0;
5154
}
5255
const patternTable = buildPattern(pattern);
53-
54-
let pIndex = pattern.length - 1;
56+
let patternLastIndex = pattern.length - 1;
57+
let pIndex = patternLastIndex;
5558
let tIndex = pIndex;
5659
while (tIndex < text.length) {
5760
if (text[tIndex] === pattern[pIndex]) {
@@ -61,8 +64,8 @@ function boyerMoore(text, pattern) {
6164
tIndex--;
6265
pIndex--;
6366
} else {
64-
tIndex += getOffset(patternTable, pIndex, text[tIndex]);
65-
pIndex = pattern.length - 1;
67+
tIndex = tIndex + (patternLastIndex - pIndex) + getOffset(patternTable, pIndex, text[tIndex]);
68+
pIndex = patternLastIndex;
6669
}
6770
}
6871
return -1;

0 commit comments

Comments
 (0)