Php implements the KMP algorithm & lt ;? Php & nbsp;/** & nbsp; * PHP implementation of KMP algorithm & nbsp; & nbsp; * & nbsp; & nbs php implements KMP algorithm
/**
* PHP implementation of KMP algorithm
*
* @ Author zhaojiangwei 2011/10/22 10:28
*/
Class KMP {
Private $ next = NULL; // The next array of the pattern string T
Private $ t = NULL; // mode string
Private $ str = NULL; // master string
Public function KMP ($ str ){
$ This-> str = str_split ($ str );
$ This-> next = array ();
}
// Return the length of the main string
Public function getStrCount (){
Return count ($ this-> str );
}
// Return results
Public function getStrPos ($ substr ){
$ Substr = str_split ($ substr );
$ This-> getNext ($ substr );
$ StrCount = $ this-> getStrCount ();
$ SubstrCount = count ($ substr );
$ SubIndex = 0; // start position of the substring
$ StrIndex = 0; // The current comparison position of the master string
While ($ subIndex <$ substrCount & ($ strCount-$ strIndex) >=( $ substrCount-$ subIndex )){
If ($ subIndex =-1 | $ this-> str [$ strIndex] ==$ substr [$ subIndex]) {
$ SubIndex ++;
$ StrIndex ++;
} Else {
$ SubIndex = $ this-> next [$ subIndex];
}
}
If ($ subIndex = $ substrCount ){
Return $ strIndex-$ substrCount;
} Else {
Return false;
}
}
// Evaluate the NEXT array of the pattern string
Public function getNext ($ t ){
If (! Is_array ($ t )){
$ T = str_split ($ t );
}
$ This-> next [0] =-1;
$ Count = count ($ t );
$ I = 0;
$ J =-1;
While ($ I <$ count ){
If ($ j =-1 | $ t [$ I] = $ t [j]) {
$ J ++;
$ I ++;
If ($ t [$ I] === t [$ j]) {
$ This-> next [$ I] = $ this-> next [$ j];
} Else {
$ This-> next [$ I] = $ j;
}
} Else {
$ J = $ this-> next [$ j];
}
}
Return $ this-> next;
}
}