KMP算法 c++ string

来源:互联网 发布:淘宝酷卡体育东西正嘛 编辑:程序博客网 时间:2024/06/09 19:10

首先是暴力解法:
之前的使用的迭代器的方法,感觉逻辑不是很清楚:

bool com(string &s1, string &s2){    auto it1 = s1.begin();    auto it2 = s2.begin();    //bool f = 0;    while (it1!= s1.end())    {        auto temp1 = it1;        auto temp2 = it2;        while (it1 != s1.end()&&*it1++== *it2++)        {            /*it1++;            it2++;*/            if (it2 == s2.end())                return 1;        }        it1 = ++temp1;        it2 = temp2;    }    return 0;}

下面是没有用迭代器的版本:

bool violentMatch(string s1, string s2){    int t1 = s1.size();    int t2 = s2.size();    int i = 0,j = 0;    while (i<t1&&j<t2)    {        if (s1[i]==s2[j])        {            i++;            j++;        }        else        {            i = i - j + 1;            j = 0;        }    }    return j == t2; //return i-j即匹配位置}

下面是KMP算法:

vector<int> getnext(string s){    int t = s.size();    vector<int> next(t);    int i = 0, j = -1;    next[0] = -1;    while (i<t-1)      //因为是算的next元素的前缀匹配数 小心越界    {        if (j==-1||s[i] == s[j])  //        {            i++;            j++;            next[i] = j;        }        else            j = next[j];    }    return next;}int KMPMatch(string s1, string s2){    int t1 = s1.size();    int t2 = s2.size();    vector <int> next(getnext(s2));    int i = 0, j = 0;    while (i < t1&&j < t2)    {        if (j == -1 || s1[i] == s2[j])  //注意是j==-1;        {            i++;            j++;        }        else        {            j = next[j];        }    }    if (j == t2)        return i - j;    return -1;}
原创粉丝点击