KMP算法的C#实现
感谢:http://www.cppblog.com/suiaiguo/archive/2009/07/16/90237.html
namespace Andersoft.KMP
{
//KMP算法最不容易理解的是Next函数,Next函数是KMP算法的精髓
public class KMP
{
//a b a b a b a b c d a b a b a b a b c d e
//-1 0 0 1 2 3 4 5 6 0 0 1 2 3 4 5 6 7 8 9 10
//a b c a b e a b c a b c f
//-1 0 0 0 1 2 0 1 2 3 4 5 3
private static int[] Next(string str)
{
int[] arr = new int[str.Length];
arr[0] = -1;
int i = -1;
int j = 0;
while (j < str.Length-1)
{
if (i == -1 || str[i] == str[j])
{
i++;
j++;
arr[j] = i;
}
else
{
i = arr[i]; //KMP算法最难理解的地方,如果不匹配,则i回至arr[i]
}
}
return arr;
}
/// <summary>
/// KMP算法
/// </summary>
/// <param name="str1">主串</param>
/// <param name="str2">匹配串</param>
/// <returns>匹配返回下标索引</returns>
public static int KMPMethod(string str1, string str2)
{
int[] arr = Next(str2);
int i = 0;
int j = 0;
while (i < str1.Length)
{
if (str1[i] == str2[j])
{
//如果是str2的最后一个字符,则两串匹配,返回索引
if (j == str2.Length - 1)
{
return i - j;
}
//如果不是str2的最后一个字符,则继续匹配两串下一个字符
else
{
i++;
j++;
}
}
//如果不匹配则j回至arr[j]处
else if (j != 0)
{
j = arr[j];
}
//如果j回至arr[j]处后仍不匹配,则继续匹配两串的下一个字符
else
{
i++;
}
}
return -1;
}
}
}