Last active
November 30, 2018 03:08
-
-
Save chuehnone/a4d6bf36129cbecc7e4f3924acdeca8c to your computer and use it in GitHub Desktop.
PHP implement Boyer–Moore algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @param string $text The string to search in. | |
* @param string $search The target string to search | |
* | |
* @return int The start index of the search string | |
*/ | |
function getStringStartIndexByBoyerMoore($text, $search) { | |
$textLength = strlen($text); | |
$searchLength = strlen($search); | |
$table = getCharRightMinDistanceTable($search); | |
$index = $searchLength - 1; | |
while($index < $textLength) { | |
for ($i = $index, $j = $searchLength - 1 ; $text[$i] == $search[$j] ; $i--, $j--) { | |
if ($j == 0) { | |
return $i; | |
} | |
} | |
$index += isset($table[$text[$index]]) ? max($table[$text[$index]], 1) : $searchLength ; | |
} | |
return -1; | |
} | |
/** | |
* @param string $text | |
* | |
* @return array | |
*/ | |
function getCharRightMinDistanceTable($text) { | |
$len = strlen($text); | |
$table = []; | |
for ($i = 0 ; $i < $len ; $i++) { | |
$table[$text[$i]] = $len - $i - 1; | |
} | |
return $table; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment