关于KMP的讲解请参考上篇《三步学通KMP》(https://blog.csdn.net/helloworldchina/article/details/104465772),这里笔者仅补充一下C#代码的实现,见下:
1 next[]数组代码:
public static int[] kmpNext(String str)
{
int[] next = new int[str.Length];
next[0] = 0;
for (int j = 1, k = 0; j < str.Length; j++)
{
while (k > 0 && str[k] != str[j])
{
k = next[k - 1];
}
if (str[j] == str[k])
{
k++;
}
next[j] = k;
}
return next;
}
2 KMP代码
public static int kmp(String s, String t, int[] next) //主串 t 模式串
{
for (int i = 0, j = 0; i < s.Length; i++)
{
while (j > 0 && s[i] != t[j])
{
j = next[j - 1]; //下一个匹配位为next数组的第j-1位
}
if (s[i] == t[j])
{
j++;//主串通过i进行加1,模式串通过j加1
}
if (j == t.Length)
{
return i - j + 1;//返回匹配位置
}
}
return -1;
}
3 打印next[]数组代码
public static void printNext(String s)
{
Console.WriteLine("********************");
int[] nextI = kmpNext(s);
Console.Write("模式串:'" + s + "'的next[]数组为:[");
for (int i = 0; i < (nextI.Length); i++)
{
Console.Write(nextI[i] + " ");
}
Console.Write("]");
Console.WriteLine();
Console.WriteLine("模式串长度为:" + nextI.Length);
}
4 主函数代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public static void Main(string[] args)
{
String s = "CDFGFABABAFABABAAAQWEDC";
String t = "ABABAA";
int[] next = kmpNext(t);
int res = kmp(s, t, next);
if (res != -1)
{
Console.WriteLine("起始位置为:" + res);
}
else Console.WriteLine("主串中不包含字符串:" + t);
printNext("ABCDABD");
printNext("ABABAA");
printNext("ABAABCAC");
Console.ReadLine();
}
5运行结果