參考:https://www.cnblogs.com/yjiyjige/p/3263858.html
public static int GetKMP(String ts, String ps)
{
char[] t = ts.ToCharArray();
char[] p = ps.ToCharArray();
int i = 0; // 主串的位置
int j = 0; // 模式串的位置
int[] next = getNext(ps);
while (i < t.Length && j < p.Length)
{
if (j == -1 || t[i] == p[j])
{ // 當j爲-1時,要移動的是i,當然j也要歸0
i++;
j++;
}
else
{
// i不需要回溯了
// i = i - j + 1;
j = next[j]; // j回到指定位置
}
}
if (j == p.Length)
{
return i - j;
}
else
{
return -1;
}
}
public static int[] getNext(String ps)
{
char[] p = ps.ToCharArray();
int[] next = new int[p.Length];
next[0] = -1;
int j = 0;
int k = -1;
while (j < p.Length - 1)
{
if (k == -1 || p[j] == p[k])
{
if (p[++j] == p[++k])
{ // 當兩個字符相等時要跳過
next[j] = next[k];
}
else
{
next[j] = k;
}
}
else
{
k = next[k];
}
}
return next;
}
Console.WriteLine(KMP.GetKMP("abcabacabaccccabacbd", "abcabd"));