Introduction: This is a detailed page for PHP to implement the KMP algorithm. It introduces the knowledge, skills, and experience related to PhP, PHP, KMP, data structure, and algorithm PHP to implement the KMP algorithm, and some PHP source code.
Class = 'pingjiaf' frameborder = '0' src = 'HTTP: // biancheng.dnbc?info/pingjia.php? Id = 360997 'rolling = 'no'>
<? PHP
/**
* 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;
}
}
Love J2EE follow Java Michael Jackson video station JSON online tools
Http://biancheng.dnbcw.info/php/360997.html pageno: 1.