暴力求解:
#include <bits/stdc++.h>
using namespace std;
#define maxSize 10
typedef struct
{
char ch[maxSize+1]; // 多出一个'\0'作为结束标记
int length;
} Str;
int index(Str S, Str T)
{
int i = 1, j = 1, k = i;
while (i<=S.length && j<=T.length)
{
if (S.ch[i] == T.ch[j])
{
++i;
++j;//继续比较后继字符
}
else
{
j = 1;
i = ++k; // 匹配失败,i从主串的下一位置开始,k中记录了上一次的起始位置
}
}
if (j>T.length) return k;
else return 0;
}
int main()
{
return 0;
}
利用next数组:
#include <bits/stdc++.h>
using namespace std;
#define maxSize 10
typedef struct
{
char ch[maxSize+1]; // 多出一个'\0'作为结束标记
int length;
} Str;
void GetNext(Str p,int next[])
{
next[1] = 0;
int i = 1;
int j = 0;
while (i < p.length)
{
//p[i]表示前缀,p[j]表示后缀
if (j == 0 || p.ch[i] == p.ch[j]) //j==0表示第一位就不匹配
{
++i;
++j;
next[i] = j;
}
else
{
j= next[j];
}
}
}
int KMP(Str S, Str T)
{
int i = 1,j = 1;
int next[T.length+1];
GetNext(T,next);
while (i <=S.length && j <=T.length)
{
//如果j = 0,或者当前字符匹配成功(即S[i] == T[j]),都令i++,j++
if (j == 0 || S.ch[i] == T.ch[j]) //j==0用来防止一开始就匹配不上的特殊情况
{
i++;
j++;
}
else
{
//如果j != 0,且当前字符匹配失败(即S[i] != T[j]),则令 i 不变,j = next[j]
//next[j]即为j所对应的next值
j = next[j];
}
}
if (j >T.length)
return i - T.length; // 匹配成功,则返回匹配的位置
else
return 0;
}
int main()
{
return 0;
}