KMP算法

#include<cstdlib>
#include<cstdio> 
#include<cstring>
#include<cmath>
#include<algorithm>

using namespace std;

void kmp(char sub[],char str[])  
{  
    int i,j;  
    int lenstr = strlen(str);  
    int lensub = strlen(sub);  
      
    int next[lensub];  
    memset(next,0,sizeof(next));  
    
    for(i = 1;i < lensub;i++)  
    {  
        j = next[i-1];      
        while(sub[i] != sub[j] && j > 0)  
        {  
            j = next[j-1];  
        }  
        if(sub[i] == sub[j])  
           {  
            next[i] = j + 1;  
        }  
        if(j > 0 && sub[i] == sub[j])
        {
            next[i-1] = next[j-1];
        }
    }  
      while(i--)
      {
          printf("%d %d\n",i,next[i]);
      }
    i = 0;  
    j = 0;  
    while(i < lenstr && j < lensub)  
    {  
        if(str[i] == sub[j])  
        {  
            i++;  
            j++;  
        }  
        else  
        {  
            if(j == 0)  
            {  
                i++;  
            }  
            else  
            {  
                j = next[j - 1];  
            }  
        }         
    }  
    if(j == lensub)  
    {  
        printf("%d\n",i-lensub);  
    }  
    else  
    {  
        printf("no!!");  
    }  
}  
  
int main()  
{  
    char substr[] = "b";
    char str[] = "aaaaabaaaaacaaabaafbdfabaabfabraakjaaaaaab";
      
    kmp(substr,str);  
      
    return 0;  
}


你可能感兴趣的:(kmp算法)