算法简介:

http://blog.sae.sina.com.cn/archives/307

绝对简单易懂,以下代码是根据算法自己实现的,为了便于阅读,分成了三个函数,可能有点ugly

另外,实际算法肯定不会调用malloc的,在这儿只是实现了功能而已

 

写了半天,我们在平常在php中调用strstr,stripos等函数时,是否会想过它的背后是这么复杂的算法吗?

 



int get_max_len(const char* search)
{
        int i,result=0;
        int len=strlen(search);
        char* copy1=(char*)malloc(2*(len+1));
        char* copy2=copy1+len+1;
        strcat(copy1, search);
        strcat(copy2, search);

        for(i=len-1;i>0;i--)
        {
                copy1[i]=0;
                copy2++;
                if(strcmp(copy1,copy2)==0)
                {
                        result=i;
                        break;
                }
        }
        free(copy1);
        return result;
}


int* prepare_rule(const char* search, int *length)
{
        int len=strlen(search);
        *length=len;
        char* copy=(char*)malloc(len+1);
        strcat(copy, search);
        int* result=(int*)malloc(sizeof(int)*len);

        while(len)
        {
                int temp=get_max_len(copy);
                result[--len]=temp;
                copy[len]=0;
        }
        free(copy);
        return result;
}

int kmp(char* src, char* search)
{
        int len;
        int* rule=prepare_rule(search,&len);

        int loc=0, already_same=0;
        char* start=src;
        while(*start)
        {
                if(*start == search[loc])
                {
                        loc++;
                        if(++already_same == len)
                                return start-src-len+1;
                }
                else
                {
                        if(already_same)
                                loc-=(already_same-rule[already_same-1]);
                        already_same=0;
                }
                start++;
        }