找出所有和模式串匹配的字符串的起始下标

/*找出所有和模式串匹配的字符串的起始下标*/
#include <iostream>
using namespace std;
void getNext(char *p,int *next)
{
    int j,k;
    next[0]=-1;
    j=0;
    k=-1;
    while(j<strlen(p)-1)
    {
        if(k==-1||p[j]==p[k])    //匹配的情况下,p[j]==p[k]
        {
            j++;
            k++;
            next[j]=k;
        }
        else                   //p[j]!=p[k]
            k=next[k];
    }
}
void getNextA(char *p,int *next)
{
    next[0]=-1;
    next[1]=0;
    for (int i=2;i<=strlen(p);i++)
    {
        int j=i-1;
        int k=next[j];
        while (true)
        {
        
            if (p[i-1]==p[k])
            {
                next[i]=next[j]+1;
                break;
            }
            else
            {
                if (k==0)
                {
                    next[i]=0;
                    break;
                }
                else
                {
                    j=k;
                    k=next[j];
                }
            }
        }
    }
}


void main()
{
    char* str="acac";
    int a[100];
    getNextA(str,a);
    for (int i=0;i<=strlen(str);i++)
    {
        cout<<a[i]<<"  ";
    }
    cout<<endl;

    char* detstr="acacacacbacacacacb";
    i=0;int j=0;
    while(i<strlen(detstr))
    {
        if (j==strlen(str))
        {
            cout<<i-strlen(str)<<endl;
            j=a[j];
        }
        if (detstr[i]==str[j])
        {
            i++;j++;
        }
        else
        {
            j=a[j];
            if (j==-1)
            {
                i++;
                j=0;
            }
        }    
    }
    if (j==strlen(str))
    {
        cout<<i-strlen(str)<<endl;
    }
}
原文地址:https://www.cnblogs.com/GoAhead/p/2658049.html