字符串的next特征函数,KMP算法,C++

来源:互联网 发布:能恢复手机数据的软件 编辑:程序博客网 时间:2024/06/05 08:05

//用KMP算法中计算字符串的next的特征函数实现过程,用c++实现

---------------------------------------------------------------------------------------------------------------------------------------------------------

#include<iostream>

#include<string.h>
using namespace std;
bool match(char p[],int i,int j)
//单纯的比较0至j, 到i-1-j到i-1是否相同?
{
    for(int t=0;t<=j;++t)
    if(p[t]!=p[i-1-j+t]) return false;
    return true;
}
 void subnext(char p[],int c[],const int sz)//  sz为第几个不同 sz=p.size
{
    if(sz<=1)
    {c[0]=-1;
    if(p[0]!=p[1]) c[1]=0;
    else c[1]=1;
     return; };
    c[0]=-1;
    if(p[0]!=p[1]) c[1]=0;
    else c[1]=1;
    for(int i=2;i<=sz;++i) //i是什么?i是第几个不同的位置。
    {
        for(int j=i-2;j>=0;--j)
        {
            //x比较 0~j,和i-1-j~i-1  是否相同;
            if(match(p,i,j)==true) c[i]=j+1;    
        }
        
    }
}
int main()
{
    const int sz=8;
    char str2[sz+1]="abaabcac";
    int c[sz]={0};
    subnext(str2,c,8);
    for(int i=0;i!=8;++i)
        cout<<c[i]<<" ";

}
0 0
原创粉丝点击