字符串模式匹配

/********************************** *输入:主串sa, 子串sb, 开始匹配位置start *输出:成功返回sb首字符在sa的位置,否则返回-1 ***********************************/

#include <iostream>
#include <string>
#include <vector>
using namespace std;

/********朴素模式匹配********************/
int StringMatch(string &sa, string &sb, unsigned start)
{
    if (sa.size() == 0 || sb.size() == 0)
        return -1;
    if (sa.size() < sb.size())
        return -1;
    unsigned starta = start, startb = 0;
    while (starta < sa.size() - sb.size() + 1)
    {
        unsigned i = starta;
        unsigned j = startb;
        while (j < sb.size())
        {           
            if (sa[i] != sb[j])
                break;
            ++i;
            ++j;
        }
        if (j == sb.size())
            return starta;
        ++starta;
    }
    return -1;
}
/******KMP模式匹配********************/
/*next*/
void GetNext(string &m, vector<int> &next)
{
    int i = -1, j = 0;
    next[0] = 0;
    while (j < int(m.size()))
    {
        if (i == -1||m[i] == m[j])
        {
            i++;
            j++;            
            next[j] = i + 1;
        }
        else
            i = next[i] - 1;
    }
    return;
}
/*nextval*/
void GetNextval(string &m, vector<int> &next)
{
    int i = -1, j = 0;
    next[0] = 0;
    while (j < int(m.size()))
    {
        if (i == -1 || m[i] == m[j])
        {
            i++;
            j++;
            if (m[i] != m[j])
                next[j] = i + 1;
            else
                next[j] = next[i];
        }
        else
            i = next[i] - 1;
    }
    return;
}
/*KMP*/
int KMPStringMatch(string &sa, string &sb, unsigned start)
{
    if (sa.size() == 0 || sb.size() == 0)
        return -1;
    if (sa.size() < sb.size())
        return -1;
    vector<int> next(sa.size() + 1);
    GetNext(sa, next);

    unsigned starta = start, startb = 0;
    while (starta < sa.size() - sb.size() + 1)
    {
        unsigned i = starta;
        unsigned j = startb;
        while (j < sb.size())
        {
            if (sa[i] != sb[j])
            {
                startb = next[j];
                break;
            }
            ++i;
            ++j;
        }
        if (j == sb.size())
            return starta;
        ++starta;
    }
    return -1;
}

int main()
{
    string a = "0000000000000000000000000000000000000001";
    string b = "00000000001";
    cout << KMPStringMatch(a, b, 0) << endl;
    return 0;
}

点赞