KMP算法 C#实现 字符串查找简单实现

时间:2023-03-09 02:54:34
KMP算法 C#实现  字符串查找简单实现

KMP算法 的C#实现,初级版本

static void Main(string[] args)
{
#region 随机字符
StringBuilder sb = new StringBuilder();
string S = "ABCDEFJHIJKLMNOPQRSTUVWXYZ0123456789";
Random r = new Random();
for (int f = ; f < ; f++)
{
if (f % == )
{
sb.Append("AABCDAABCD");
}
else
{
sb.Append(S.Substring(r.Next(, S.Length - ), ));
} }
string sourceStr = sb.ToString();
Console.WriteLine("待匹配的字符长度为:" + sourceStr.Length);
#endregion
Console.WriteLine("start");
Stopwatch sw = new Stopwatch();
sw.Start();
string ostr = "AABCDAABCD";//目标字符
/*
找到对应位置的最大移动长度
*/
Dictionary<int, int> dic = GetMaxMoveLength(ostr);
int success = ;
for (int i = ; i < sourceStr.Length; i++)
{
int j = ;
while (j < ostr.Length && i + j < sourceStr.Length && ostr[j] == sourceStr[i + j])
{
j++;
}
if (j == ostr.Length)
{
success++;
}
i += j;
}
sw.Stop();
Console.WriteLine("成功" + success+"个");
Console.WriteLine("时间:"+sw.ElapsedMilliseconds+"毫秒");
Console.WriteLine("End");
Console.ReadKey();
}
static Dictionary<int, int> GetMaxMoveLength(string ostr)
{
Dictionary<int, int> CanMoved = new Dictionary<int, int>();
for (int i = ; i < ostr.Length; i++)
{
List<string> q = new List<string>();
List<string> h = new List<string>();
string tempstr = ostr.Substring(, i + );
for (int j = ; j < tempstr.Length; j++)
{
q.Add(tempstr.Substring(, j));
}
for (int j = tempstr.Length - ; j > ; j--)
{
h.Add(tempstr.Substring(j, tempstr.Length - j));
}
//获取该位置的最大长度
IEnumerable<string> keys = q.Intersect(h);
int movelength = ;
foreach (string s in keys)
{
if (s.Length > movelength)
{
movelength = s.Length;
}
}
CanMoved.Add(i, i-movelength);
}
return CanMoved;
}

KMP算法 C#实现  字符串查找简单实现

在42万5000个字符中匹配到25000个目标字符用时10毫秒