KMP算法 C#实现 字符串查找简单实现
2017-08-25 13:08
661 查看
KMP算法 的C#实现,初级版本
View Code
在42万5000个字符中匹配到25000个目标字符用时10毫秒
static void Main(string[] args) { #region 随机字符 StringBuilder sb = new StringBuilder(); string S = "ABCDEFJHIJKLMNOPQRSTUVWXYZ0123456789"; Random r = new Random(); for (int f = 0; f < 100000; f++) { if (f % 4 == 0) { sb.Append("AABCDAABCD"); } else { sb.Append(S.Substring(r.Next(1, S.Length - 4), 4)); } } 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 = 0; for (int i = 0; i < sourceStr.Length; i++) { int j = 0; 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 = 0; i < ostr.Length; i++) { List<string> q = new List<string>(); List<string> h = new List<string>(); string tempstr = ostr.Substring(0, i + 1); for (int j = 1; j < tempstr.Length; j++) { q.Add(tempstr.Substring(0, j)); } for (int j = tempstr.Length - 1; j > 0; j--) { h.Add(tempstr.Substring(j, tempstr.Length - j)); } //获取该位置的最大长度 IEnumerable<string> keys = q.Intersect(h); int movelength = 0; foreach (string s in keys) { if (s.Length > movelength) { movelength = s.Length; } } CanMoved.Add(i, i-movelength); } return CanMoved; }
View Code
在42万5000个字符中匹配到25000个目标字符用时10毫秒
相关文章推荐
- c# 用 FileStream类简单实现向一个文本里写字符串
- 如何用C#在winform中实现简单的查找功能
- c# 进程间的通信实现之一简单字符串收发
- C#简单实现发送socket字符串
- 关于记事本的“查找下一个”以及“向上向下”,C#.net的一个简单实现
- C#实现字符串转换成字节数组的简单实现方法
- 最简单的字符串加密C#实现-移位加密
- C#实现String.IndexOf功能 查找字符串
- KMP算法 C#简单实现
- Python简单实现查找一个字符串中最长不重复子串的方法
- c#打包文件解压缩 C#中使用委托、接口、匿名方法、泛型委托实现加减乘除算法 一个简单例子理解C#的协变和逆变 对于过长字符串的大小比对
- 用C#实现简单的字幕动态叠加效果
- 用c#实现类似QQ的简单通讯程序
- 如何C#中实现在TreeView查找某一节点
- C#简单实现的远程命令程序
- C#中简单实现多线程
- C#中利用正则表达式实现字符串搜索
- C#的E_mail发送简单实现
- C#2.0 - Object Pool 简单实现
- 用C#实现基于查寻字符串的文件行查询器(3)-设计与实现