数据结构——KMP算法

#include <iostream>
using namespace std;

#define MaxStrSize 256
typedef unsigned
char MyString[MaxStrSize+1]; //0号单元存放串的长度
int next[5];
/*
掩饰符号类型。例如当需要定义多个包含80个元素的数组a,b,c时,可以这样定义:
typedef char Array_eighty[80];
Array_eighty a,b,c;

也可以这样隐藏指针:
typedef char * pstr;
int mystrcmp(pstr, pstr);
*/

//打印串
void StrPrint(MyString &S)
{
if(S[0]<=0)
{
cout
<<"空串!"<<endl;
}
else
{
int i=1;
while(S[i] != '\0')
{
cout
<<S[i];
i
++;
}
}
}
//给串赋值
void Build_MyString(MyString s,char *str)
{
int length=strlen(str);
s[
0]=length;
int i=0;
while(str[i]!='\0')
{
s[i
+1]=str[i];
i
++;
}
s[i
+1]='\0';
}
//求模式串T的next函数的并存入数组next[]中
void get_next(MyString s2,int next[])
{
int i=1;
next[
1]=0;
int j=0;
while(i<s2[0])
{
if(j==0 || s2[i]==s2[j])
{
i
++;
j
++;
next[i]
=j;
}
else
j
=next[j];
}
}
//模式匹配
int Index_KMP(MyString s1,MyString s2)
{
//返回子串t在主串s中第pos个字符之后的位置。如不存在返回0。
int i=1,j=1;

while(i<=s1[0] && j<=s2[0])
{
if(j==0 || s1[i]==s2[j]) //继续进行后续字符串的比较
{
i
++;
j
++;
}
else
{
j
=next[j]; //模式串向右移动
}
}
if(j>s2[0]) //匹配成功
return i-s2[0];
else
return 0;
}

int main()
{
MyString S1;
char *str1="ababcabcacbab";
Build_MyString(S1,str1);
cout
<<S1[0]-0<<endl; //将0号单元存放的串的长度变换为整型输出
StrPrint(S1);
cout
<<endl;

MyString S2;
char *str2="abcac";
Build_MyString(S2,str2);
cout
<<S2[0]-0<<endl;
StrPrint(S2);

get_next(S2,next);
cout
<<endl<<Index_KMP(S1,S2)<<endl;
return 0;
}

 

posted @ 2010-07-31 20:39  忧国忧铭  Views(377)  Comments(0)    收藏  举报