KMP

来源:互联网 发布:mobi格式软件ios 编辑:程序博客网 时间:2024/06/03 12:20
/*KMP算法时间复杂度:O(主串长度加上子串长度)空间复杂度:O(主串长度加上子串长度再加上next数组的长度(与子串长度相同))*/#include <iostream>#include <string>#include <algorithm>using namespace std;void gets_next(string T, int len, int *next){    int i = 1;    int j = 0;    next[1] = 0;    while(i < len)    {        if(j==0 || T[i-1] == T[j-1])        {            ++i;            ++j;            if(T[i-1]!=T[j-1])                next[i] = j;            else                next[i] = next[j];        }        else            j = next[j];    }    cout << "next数组如下:" << endl;    for(int t = 1; t <= len; t++)        cout << next[t] << " ";    cout << endl;}int KMP(string S, int len1, string T, int len2, int pos)//pos为起始位{    int i = pos;    int j = 1;    int next[len2+1];    gets_next(T, len2, next);    while(i <= len1 && j <= len2)    {        if(j==0 || S[i-1] == T[j-1])        {            ++i;            ++j;            if(j > len2)//找到匹配            return i - len2;//返回首位下标        }        else        {            j = next[j];        }    }    return 0;}int main(){    string str = "aaaaaaab";    string str1 = "aaaaabbaaaaaaabaa";    int num = KMP(str1, str1.size(), str, str.size(), 1);    if(num!=0)        cout << "子串在主串中的起始位置为 " << num;    else        cout << "主串不存在与子串相匹配的串";    return 0;}

0 0
原创粉丝点击