首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

关于KMP匹配的有关问题

2012-05-16 
关于KMP匹配的问题#include stdio.h#include malloc.htypedef struct//定义串{char ch[20]int len}s

关于KMP匹配的问题
#include <stdio.h>
#include <malloc.h>
typedef struct//定义串
{
char ch[20];
int len;
}sstring;
//全局变量
int len1,len2;
char b1[20],b2[20];
sstring *a1,*a2;

int getstring(sstring *a,char b[20])//输入的字符赋值到字符串
{
int i=0;
a->len=0;
while(b[i]!='\0')
{
a->ch[i]=b[i];
i++;
a->len++;
}
return a->len;
}
void iflegal(int len1,int len2)//判断模式串长度是否小于主串
{
if(len1==0||len2==0||len1<len2)
{
printf("输入错误,重新输入:\n");
printf("输入主串:\n");
scanf("%s",&b2);
len1=getstring(a1,b1);

printf("输入模式串:\n");
scanf("%s",&b2);
len2=getstring(a2,b2);
iflegal(len1,len2);
}
}

int kmp(sstring *a1,sstring *a2)//kmp匹配
{//求next
int i=1,j=0,next[50];
next[1]=0;
while(i>=a2->len)
{
if((a2->ch[i]=a2->ch[j])||(j==0))
{
i++;j++;
next[i]=j;
}
else
j=next[j];
}
//求模式串在主串中位置
i=0;j=0;
int k;
while((a1->len>i)&&(a2->len>j))
{
if(a1->ch[i]=a2->ch[j])
{i++;j++;}
else
j=next[j+1];
}

if(j>=a2->len)
k=i-a2->len;
else
k=0;
return k;
}
void main()
{
a1=(sstring *)malloc(sizeof(sstring));
a2=(sstring *)malloc(sizeof(sstring));
printf("输入主串:\n");
scanf("%s",&b1);
len1=getstring(a1,b1);

printf("输入模式串:\n");
scanf("%s",&b2);
len2=getstring(a2,b2);
iflegal(len1,len2);
int n;
n=kmp(a1,a2);
printf("模式串在主串的第一匹配位置为:%d\n",n);
}

运行结果错误谁能帮我指出哪错了 该怎么改

[解决办法]

C/C++ code
while(i>=a2->len)
[解决办法]
我以前写过一个,LZ拿去看看

C/C++ code
void GetNext(const string& strMatch, vector<int>& nextVector){    nextVector.resize(strMatch.size());    nextVector[0] = -1;    int m = -1, n = 0;    while (n < strMatch.size() - 1)    {        if (m == -1 || strMatch[n] == strMatch[m])        {            n++, m++;            if (strMatch[n] != strMatch[m])            {                nextVector[n] = m;            }            else            {                nextVector[n] = nextVector[m];            }        }        else        {            m = nextVector[m];        }    }}int Index::StringIndex_KMP(const string& strIn, const string& strMatch, int nPos){    vector<int> nextVector;    GetNext(strMatch, nextVector);    int n = nPos;    int m = 0;    while (n < (int)strIn.size() && m < (int)strMatch.size())    {        if (m == -1 || strIn[n] == strMatch[m])        {            n++, m++;        }        else        {            m = nextVector[m];        }    }    if (m == strMatch.size())    {        return n - m;    }    return -1;}
[解决办法]
C/C++ code
if(a1->ch[i]=a2->ch[j]) 

热点排行