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

时间:2022-07-24
本文章向大家介绍KMP算法 C#实现 字符串查找简单实现,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

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;
        }

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