KMP算法(C语言版)

有关字符串匹配的最有效的算法。

其算法复杂度为两个字符串的长度之和(m+n)。

#include <stdio.h>
#include <string.h>

void setnext(char t[], int next[])
{
    next[0]=-1;
    int i;
    for(i=1; i<strlen(t); i++) {
        int j = next[i-1];
        while(t[i] != t[j+1] && j >= 0)
            j = next[j];
        if(t[i] == t[j+1])
            next[i] = j+1;
        else
            next[i] = 0;
    }
}

int count_kmp(char s[], char t[], int next[])
{
    int t_size = strlen(t);
    setnext(t, next);
    int index, count = 0;
    for(index=0; index<strlen(s); ++index){
        int pos = 0;
        int iter = index;
        while(pos<t_size && iter<strlen(s)){
            if(s[iter] == t[pos]){
                ++iter;
                ++pos;
            } else {
                if(pos == 0)
                    ++iter;
                else
                    pos = next[pos-1] + 1;
            }
        }//whileend
        if(pos==t_size && (iter-index)==t_size)
            ++count;
    }//forend
    return count;
}

int main(void)
{
    char s[]="abaabcacabaabcacabaabcacabaabcacabaabcac";
    char t[]="ab";
    int next[strlen(t)];
    int count = count_kmp(s, t, next);
    printf("count=%d\n", count);
    return 0;
}

你可能感兴趣的:(字符串,kmp算法)