Add Boyer-Moore string search algorithm (#990)

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
This commit is contained in:
Ayoade David
2022-04-23 12:06:41 +01:00
committed by GitHub
parent c81db629b8
commit 7881cb5f16
2 changed files with 50 additions and 0 deletions

View File

@ -295,6 +295,7 @@
## String
* [AlphaNumericPalindrome](https://github.com/TheAlgorithms/Javascript/blob/master/String/AlphaNumericPalindrome.js)
* [AlternativeStringArrange](https://github.com/TheAlgorithms/Javascript/blob/master/String/AlternativeStringArrange.js)
* [BoyerMoore](https://github.com/TheAlgorithms/Javascript/blob/master/String/BoyerMoore.js)
* [CheckAnagram](https://github.com/TheAlgorithms/Javascript/blob/master/String/CheckAnagram.js)
* [CheckCamelCase](https://github.com/TheAlgorithms/Javascript/blob/master/String/CheckCamelCase.js)
* [CheckExceeding](https://github.com/TheAlgorithms/Javascript/blob/master/String/CheckExceeding.js)

49
String/BoyerMoore.js Normal file
View File

@ -0,0 +1,49 @@
/*
*
*
*Implementation of the Boyer-Moore String Search Algorithm.
*The BoyerMoore string search algorithm allows linear time in
*search by skipping indices when searching inside a string for a pattern.
*
*
*
*
**/
const buildBadMatchTable = (str) => {
const tableObj = {}
const strLength = str.length
for (let i = 0; i < strLength - 1; i++) {
tableObj[str[i]] = strLength - 1 - i
}
if (tableObj[str[strLength - 1]] === undefined) {
tableObj[str[strLength - 1]] = strLength
}
return tableObj
}
const boyerMoore = (str, pattern) => {
const badMatchTable = buildBadMatchTable(pattern)
let offset = 0
const patternLastIndex = pattern.length - 1
const maxOffset = str.length - pattern.length
// if the offset is bigger than maxOffset, cannot be found
while (offset <= maxOffset) {
let scanIndex = 0
while (pattern[scanIndex] === str[scanIndex + offset]) {
if (scanIndex === patternLastIndex) {
// found at this index
return offset
}
scanIndex++
}
const badMatchString = str[offset + patternLastIndex]
if (badMatchTable[badMatchString]) {
// increase the offset if it exists
offset += badMatchTable[badMatchString]
} else {
offset++
}
}
return -1
}
export { boyerMoore }