Skip to content

Instantly share code, notes, and snippets.

@adrianosferreira
Last active December 5, 2019 13:01
Show Gist options
  • Save adrianosferreira/81f112f8a5725a8573c1b309fc60dd5a to your computer and use it in GitHub Desktop.
Save adrianosferreira/81f112f8a5725a8573c1b309fc60dd5a to your computer and use it in GitHub Desktop.
KMP substring search, longest prefix suffix in PHP
<?php
function buildLPS( $string ) {
$lps = [ 0 ];
$i = 0;
$j = $i + 1;
while ( strlen( $string ) > count( $lps ) ) {
if ( $string[ $i ] === $string[ $j ] ) {
$lps[ $j ] = $i + 1;
$i ++;
$j ++;
} elseif ( $i === 0 ) {
$lps[ $j ] = 0;
$j ++;
} else {
$i = $lps[ $i - 1 ];
}
}
return $lps;
}
function kmpIsTherePattern( $string, $pattern ) {
$lps = buildLPS( $pattern );
$i = 0;
$j = 0;
while ( $j < strlen( $string ) ) {
if ( $string[ $j ] === $pattern[ $i ] ) {
if ( $i === strlen( $pattern ) - 1 ) {
return [ 'start' => $j - strlen( $pattern ) + 1, 'end' => $j ];
}
$i ++;
$j ++;
} elseif ( $i === 0 ) {
$j ++;
} else {
$i = $lps[ $i - 1 ];
}
}
return false;
}
var_dump( kmpIsTherePattern( 'abcxabcdabxabcdabcdabcy', 'abcdabcy' ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment