#include<iostream>
#define defaultsize 30
using namespace std;
typedef struct {
char*ch;
int maxsize;
int n;
}HString;
void HStringInit(HString&S, int n=defaultsize)
{
if (n < defaultsize)
n = defaultsize;
S.ch = new char[n];
S.maxsize = n;
S.n = n;
}
void CreateHString(HString&S, char c[])
{
int i = 0;
while (c[i] != '\0'&&i<S.maxsize)
{
S.ch[i] = c[i];
i++;
}
if (c[i] != '\0')
cout << "超出存储空间" << endl;
else
S.n = i;
}
void Print(HString&S)
{
for (int i = 0;i < S.n;i++)
cout << S.ch[i] << " ";
}
int find(const HString&T, const HString&P)
{
for (int i = 0;i < T.n - P.n+1;i++)
{
int j = 0;
for (j = 0;j < P.n;j++)
{
if (P.ch[j] != T.ch[j + i])
break;
}
if (j == P.n&&P.ch[j] == T.ch[i+j])
{
return i;
}
}
}
void GetNext(HString&S, int next[])
{
int j = 0, k = -1;next[j] = k;
while(j<S.n)
{
while (k >= 0 && S.ch[k] != S.ch[j])k = next[k];
j++;k++;
if (S.ch[k] == S.ch[j])next[j] = next[k];
else next[j] = k;
}
}
int FastFind(HString&T, HString&P,int next[])
{
int i = 0, j = 0;
while (i < T.n&&j < P.n)
{
if (j == -1 || T.ch[i] == P.ch[j]) { i++;j++; }
else j = next[j];
}
if (j < P.n)return -1;
else return i - P.n;
}
int main()
{
HString S1;
HString S2;
HStringInit(S1);
HStringInit(S2);
char c1[] = "dad";
char c2[] = "aadad";
CreateHString(S1, c1);
CreateHString(S2, c2);
Print(S1);
Print(S2);
int next[sizeof(c1) / sizeof(char)];
GetNext(S1, next);
cout << FastFind(S2, S1, next);
system("pause");
}
C++KMP字符串匹配
最新推荐文章于 2021-04-23 18:59:47 发布