求字符数组Next数组
/// <summary>
/// 求出一个字符串的next数组
/// </summary>
/// <param name="t">字符串</param>
/// <returns>next数组</returns>
static int[] getNextArray(string t)
{
int[] next = new int[t.Length];
next[0] = -1;
next[1] = 0;
int k;
for (int j = 2; j < t.Length; j++)
{
k = next[j - 1];
while (k != -1)
{
if (t[j - 1] == t[k])
{
next[j] = k + 1;
break;
}
else
{
k = next[k];
}
next[j] = 0; //当k==-1 跳出循环是,next[j] = 0, 否则next[j]会在break之前被赋值
}
}
return next;
}
对主串S和模式串T进行KMP模式匹配
/// <summary>
/// 对主串s和模式串t进行KMP模式匹配
/// </summary>
/// <param name="s">主串/param>
/// <param name="t">模式串</param>
/// <returns>若匹配成功,返回t在s中的位置(第一个相同字符对应的位置),若匹配失败,返回-1</returns>
public static int kmpMatch(string s, string t)
{
int[] next = getNextArray(t);
int i = 0, j = 0;
while (i < s.Length && j < t.Length)
{
if (j == -1 || s[i] == t[j])
{
i++;
j++;
}
else
j = next[j];
}
if (j == t.Length)
{
return i - j;
}
else
return -1;
}