Overview
?? KMP algorithm I think there are two key points: 1. Calculate a partial match table for a pattern string (at this point, compare yourself to yourself) 2. When the main string is matched, the main string is only traversed once, and the matching table calculates where the pattern string should move, depending on the part of the pattern string. The time complexity of the KMP algorithm is O (m+n); The algorithm code (PHP) I implemented below
theory
About the KMP theory section, this article is well written: http://kb.cnblogs.com/page/176818/. I will not dwell on it.
calculate partial Match table
function kmp_next($string){ $length= Strlen ($string);//Get string length $next[0] =0;$j=0;$i=1; while($i<$length){if($string{$j} ==$string{$i}){$j++;$next[$i]=$j;$i++; }Else if($j==0){$next[$i] =$j;$i++; }Else{$j=$next[$j]; } }return $next;}
KMP Algorithm
function kmp($text,$mode){ $t _length= Strlen ($text);$m _length= Strlen ($mode);if($t _length<$m _length){return-1; }$arr= Kmp_next ($mode);$j=0;$i=0; while($i<$t _length){if($text{$i}==$mode{$j}){if($j<$m _length-1){$j++;$i++; }Else{return $i-$m _length+1; } }Else if($j==0){$i++; }Else{$j=$arr[$j-1]; } }return-1;}
called
$string‘BBC ABCDAB ABCDABCDABDE‘;$mode‘ABCDABD‘;$key = kmp($string,$mode);var_dump(kmp_next($mode));var_dump($key);var_dump(substr($string,$key,strlen($mode)));
Results
KMP string pattern matching algorithm