Advertisement
cahyadsn

boyer moore algorithm

May 26th, 2016
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.94 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * Returns the index of the first occurrence of the
  5. * specified substring. If it's not found return -1.
  6. *
  7. * @param text The string to be scanned
  8. * @param pattern The target string to search
  9. * @return The start index of the substring
  10. */
  11. function BoyerMoore($text, $pattern) {
  12.     $patlen = strlen($pattern);
  13.     $textlen = strlen($text);
  14.     $table = makeCharTable($pattern);
  15.  
  16.     for ($i=$patlen-1; $i < $textlen;) {
  17.         $t = $i;
  18.         for ($j=$patlen-1; $pattern[$j]==$text[$i]; $j--,$i--) {
  19.             if($j == 0) return $i;
  20.         }
  21.         $i = $t;
  22.         if(array_key_exists($text[$i], $table))
  23.             $i = $i + max($table[$text[$i]], 1);
  24.         else
  25.             $i += $patlen;
  26.     }
  27.     return -1;
  28. }
  29.  
  30. function makeCharTable($string) {
  31.     $len = strlen($string);
  32.     $table = array();
  33.     for ($i=0; $i < $len; $i++) {
  34.         $table[$string[$i]] = $len - $i - 1;
  35.     }
  36.     return $table;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement