Php cash KMP algorithm

Source: Internet
Author: User
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;
}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.