KMP字符串匹配

时间:2023-08-13 11:34:44
 #include<iostream>

 using namespace std;

 #define MAX    255

 typedef unsigned char BYTE;

 typedef BYTE String[MAX+];

 bool strAssign(String& strTemp,char* Temp);   //定长字符串存储
bool strTravel(String& strTemp);          //打印
void KMP(String& strMother,String& strSon,int* pData);
void GetNext(String& strSon,int* pNext);
                                        //KMP算法的实现要求两个子函数 KMP() 和GetNext() void main()
{ String strMother;
memset(strMother,,sizeof(strMother)); String strSon;
memset(strSon,,sizeof(strSon)); strAssign(strMother,"HHHeHeHHe");
strAssign(strSon,"HeHe"); strTravel(strMother);
strTravel(strSon);
int* pData = (int*)malloc(sizeof(int)*(strMother[]+)); KMP(strMother,strSon,pData); int i = ;
for(i=;i<=pData[];i++)
{
cout<<pData[i]<<" "; }
cout<<endl; }
bool strAssign(String& strTemp,char* Temp)
{
strTemp[] = strlen(Temp); int i = ;
for(i=;i<=strTemp[];i++)
{
strTemp[i] = Temp[i-]; } return true; }
bool strTravel(String& strTemp)
{
int i = ;
for(i=;i<=strTemp[];i++)
{
cout<<strTemp[i]<<" "; } cout<<endl;
return true; }
void KMP(String& strMother,String& strSon,int* pData)
{
int* pNext = (int*)malloc(sizeof(int)*(strSon[]+)); GetNext(strSon,pNext); int i = ;
int j = ;
int k = ; while(i<=strMother[])
{
if(i==||strMother[i]==strSon[j])
{
i++;
j++; }
else
{
j = pNext[j]; } if(j>strSon[])
{
pData[k] = i-strSon[];
k++;
j=; } } pData[] = k-;
free(pNext); }
void GetNext(String& strSon,int* pNext)
{
pNext[] = ; int i = ;
int j = ; while(i!=strSon[])
{
if(j==||strSon[i]==strSon[j])
{
i++;
j++; pNext[i] = j; }
else
{
j = pNext[j]; } }
}