<String matching> KMP algorithm than violence to solve why the time is less complex?

represents a text string str, m represents a pattern string;

str [i] and m [j] matches the character is being compared;

 

KMP time complexity is O (m + n), violence, is to solve the time complexity O (m * n)

 

KMP utilizes m [0: j-1] and str [ij: i-1] that is the same, but obviously can not solve violence.

 

int kmp(string str,string m)
{
    int next[MAXN];
    next[0] = -1;
    int i=0;
    int j=-1;
    while(i<m.size())
    {
        if(j==-1 || m[i]==m[j])
        {
            i++;
            j++;
            next[i] = j;
        }
        else
        {
            j = next[j];
        }
    }

    i=0;
    j=0;
    while(i<str.size() && j<m.size())
    {
        if(j==-1 || str[i]==m[j])
        {
            i++;
            j++;
        }
        else
        {
            j =next[j];
        }
     if(j==m.size()-1)
     {
      return i-j;
     } }
   return -1; }

 

Guess you like

Origin www.cnblogs.com/dynmi/p/12497500.html