
using System;
using System.Collections.Generic;
using System.Linq;
namespace KMP
{
class Program
{
static void Main(string[] args)
{
string s = "ABCDAABEFAECA";
string comp = "AECA";
sss(s, comp);
Console.Read();
}
private static void sss(string s, string comp)
{
int j = 0;
for (int i = 0; i < s.Length;)
{
if (s[i] != comp[j])
{
//i--;
//判断需要跳过几个
int temp = j - Pd(j, comp);
if (temp==1)
{
i--;
}
if (temp==0)
{
i++;
}
j = 0;
i += temp;
}
else
{
j++;
i++;
if (j == comp.Length)
{
Console.WriteLine("找到了匹配的字符串,---->位置在:{0}", i - j );
return;
}
}
}
Console.WriteLine("没有找到哦");
//匹配成功的表现是什么?
}
/// <summary>
/// 移动位数=已匹配的字符数-对应的部分匹配值
/// </summary>
private static int Pd(int j, string comp)
{
comp = comp.Substring(0, j);
//要得到前缀和,后缀
int bf1 = bf(qian(comp), hou(comp));
return bf1;
}
public static string[] qian(string comp)
{
List<string> tStr = new List<string>();
string s = string.Empty;
for (int i = 0; i < comp.Length - 1; i++)
{
s += comp[i];
tStr.Add(s);
}
return tStr.ToArray();
}
public static string[] hou(string comp)
{
List<string> tStr = new List<string>();
string s = string.Empty;
for (int i = comp.Length - 1; i > 0; i--)
{
s = comp.Substring(1, i);
tStr.Add(s);
}
return tStr.ToArray();
}
/// <summary>
/// 对应部分匹配值
/// </summary>
/// <param name="f"></param>
/// <param name="b"></param>
/// <returns></returns>
public static int bf(string[] f, string[] b)
{
//查看重复的次数
int j = 0;
for (int i = 0; i < f.Length; i++)
{
if (f.Contains(b[i]))
{
j++;
}
}
return j;
}
}
}
Hold on, everything is possible.