模式匹配的定义:主串s中寻找子串t 的过程,子串t 称为模式。如果匹配成功,则返回t在s中第一次出现的位置。如:主串s:“ababc”匹配子串t:“abc”的结果为2(下标从0开始)。
实现算法:
1. BF算法
todo。。。
2. KMP算法
KMP算法中,主串不需要回溯。
int kmp(char *s, char *t)
{
void initNextArray(char *t, int *next, int n);
int index = -1;
int len = strLen(t);
int *next = new int[len];
int i = 0;
int j = 0;
initNextArray(t, next, len);
while (s[i] != '\0' && t[j] != '\0')
{
if (s[i] == t[j])
{
i++;
j++;
}
else
{
j = next[j];
if (j == -1)
{
i++;
j++;
}
}
}
delete next;
return index;
}
void initNextArray(char *t, int *next, int n)
{
next[0] = -1;
next[1] = 0;
for (int i = 2; i < n; i++)
{
if (t[i - 1] == t[next[i - 1]])
{
next[i] = next[i - 1] + 1;
}
else
{
next[i] = 0;
}
}
}