字符串匹配

来源:互联网 发布:周杰伦侯佩岑 知乎 编辑:程序博客网 时间:2024/05/29 17:50
/*    字符串匹配:> BM->KMP*/int func(char*s, char*p){    int i = 0;    int j = 0;    while (i < strlen(s))    {        j = 0;        while (s[i] == p[j] && j < strlen(p))        {            j++;            i++;        }        if (j == strlen(p))            return i - j;        i = i - j + 1;    }    return -1;}void getNext(char*p, int *next){    next[0] = -1;    int slow = -1;    int fast = 0;    while (fast < strlen(p) - 1)    {        if (slow == -1 || p[slow] == p[fast])        {            slow++;            fast++;            next[fast] = slow;        }        else            slow = next[slow];    }}int KMP(char*s, char*p){    int next[100];    int i = 0;    int j = 0;    getNext(p, next);    while (i < strlen(s))    {        if (j == -1 || s[i] == p[j])        {            ++i;            ++j;        }        else        {            j = next[j];        }        if (j == strlen(p))            return i - strlen(p);    }    return -1;}

关于next数组和KMP参见链接:
http://note.youdao.com/share/?id=f9906cb0d53a384435d83d66b59fafa5&type=note

http://note.youdao.com/share/?id=2312592fd636b64f270d18240dbb0268&type=note

2 0