KMP String Matching Algorithm

In the process of processing strings, we often encounter string matching problems, such as finding whether a string appears in another string, how many times it appears, where it appears, and so on. Among them, we call the main string "text string" (text), and call the substring that needs to be found in the main string "pattern string". For example, if you want to find the string "abab" in "aababababc", then "aababababc" is the text string and "abab" is the pattern string.

For this kind of problem, the brute force solution is to enumerate the starting position of the pattern string in the text string, and then match one by one, and the exact match means that it has been found. code show as below

int l1=text.size(),l2=pattern.size();
for(int i=0;i<l1-l2+1;i++)
{
    bool flag=false;
    for(int a=i,b=0;b<l2;a++,b++)
        if(text[a]!=pattern[b])
        {
            flag=true;
            break;
        }
    if (!flag) printf( " Found a pattern string at position %d of the text string\n " ,i);
}

It is not difficult to see that such a time complexity is O(nm), and the KMP algorithm can solve this problem in O(n+m) time (n and m are the lengths of text strings and pattern strings, respectively).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325120466&siteId=291194637