这题就是KMP算法,看了几遍还是没能想起来,又拿起书看了看,写了程序,bug不少,调了好久,通了。
char *strStr(char *haystack, char *needle) {
if (haystack==NULL||needle==NULL)
{
return NULL;
}
int lenneedle=0;
char *p=needle;
while(*p)
{
p++;
lenneedle++;
}
int *nextval = new int[lenneedle];
nextval[0] = -1;
int i=0,j=-1;
while(i<lenneedle-1)//this is vital
{
if (j==-1||needle[i]==needle[j])
{
++i;
++j;
if (needle[i]!=needle[j])
nextval[i] = j;
else
nextval[i] = nextval[j];
}
else
j = nextval[j];
}
int hi=0;
int ni=0;
while(*haystack&&ni<lenneedle)
{
if (ni==-1||*haystack==needle[ni])
{
haystack++;
ni++;
}
else
ni = nextval[ni];
}
delete[] nextval;
if (ni>=lenneedle)
{
return haystack - lenneedle;
}
else
return NULL;
}char str1[20]="acabaabaabcacaabc";
char str2[]="abaabcac";
cout<<strStr(str1,str2)<<endl;
采用的是严蔚敏那本书上的程序和例子。

本文深入探讨了KMP算法的原理与应用,通过实例代码展示了如何使用该算法解决字符串匹配问题。从理论到实践,逐步解析算法核心,提供调试经验分享。
220

被折叠的 条评论
为什么被折叠?



