以下是一个使用C#实现KMP算法的示例代码:
using System;
class KMPAlgorithm
{
public static int KMPSearch(string text, string pattern)
{
int n = text.Length;
int m = pattern.Length;
// 构建部分匹配表
int[] lps = new int[m];
ComputeLPSArray(pattern, m, lps);
// 在文本中搜索模式
int i = 0; // 文本指针
int j = 0; // 模式指针
while (i < n)
{
if (text[i] == pattern[j])
{
i++;
j++;
}
if ( == m)
{
return i - j; 找到匹配,返回匹配的起始位置
}
else if (i < n && text[i] != pattern[j])
{
if (j != 0)