C#实现KMP算法,在长字符串中找到第一个符合要求的子字符串

KMP算法可以查找符合要求的字符串的索引。

在下面的代码中会打印出方法所消耗的时间。

一些异常的处理:

  1. 比如当word比longwrod还要长的时候异常处理
  2. longwrod或者word为空的时候异常处理
  3. 当word在longwrod中不存在的时候异常处理
csharp 复制代码
       static void Main(string[] args)
        {
            string longwrod = "112312er3338bluifaehilf";
            string word = "3338";
            DateTime beforDT = System.DateTime.Now;
            TMPFunc(longwrod, word);
            DateTime afterDT = System.DateTime.Now;
            TimeSpan ts = afterDT.Subtract(beforDT);
            Console.WriteLine("DateTime总共花费{0}ms.", ts.TotalMilliseconds);
		
        }

        /// <summary>
        /// TMP算法_查找符合要求的字符串的索引
        /// </summary>
        /// <param name="longWord"> 长串</param>
        /// <param name="word">字串</param>
        public static void TMPFunc(string longWord, string word)
        {
            if (string.IsNullOrEmpty(longWord) || string.IsNullOrEmpty(word))
            {
                Console.WriteLine("长字符串和查找字符串不能为空。");
                return;
            }

            if (word.Length > longWord.Length)
            {
                Console.WriteLine("查找字符串长度大于长字符串长度,无法匹配。");
                return;
            }

            int[] prefixTable = CalculatePrefixTable(word);
            int longWordIndex = 0;
            int wordIndex = 0;

            while (longWordIndex < longWord.Length)
            {
                if (longWord[longWordIndex] == word[wordIndex])
                {
                    longWordIndex++;
                    wordIndex++;

                    if (wordIndex == word.Length)
                    {
                        // 找到了匹配
                        Console.WriteLine("匹配找到在索引 " + (longWordIndex - wordIndex));
                        wordIndex = prefixTable[wordIndex - 1];
                    }
                }
                else
                {
                    if (wordIndex != 0)
                    {
                        wordIndex = prefixTable[wordIndex - 1];
                    }
                    else
                    {
                        longWordIndex++;
                    }
                }
            }

            if (wordIndex == 0)
            {
                Console.WriteLine("未找到匹配。");
            }
        }

        private static int[] CalculatePrefixTable(string word)
        {
            int[] prefixTable = new int[word.Length];
            int prefixLength = 0;
            int i = 1;

            while (i < word.Length)
            {
                if (word[i] == word[prefixLength])
                {
                    prefixLength++;
                    prefixTable[i] = prefixLength;
                    i++;
                }
                else
                {
                    if (prefixLength != 0)
                    {
                        prefixLength = prefixTable[prefixLength - 1];
                    }
                    else
                    {
                        prefixTable[i] = 0;
                        i++;
                    }
                }
            }

            return prefixTable;
        }
相关推荐
sheeta19981 分钟前
LeetCode 每日一题笔记 日期:2026.04.21 题目:1722. 执行交换操作后的最小汉明距离
笔记·算法·leetcode
鲸渔18 分钟前
【C++ 跳转语句】break、continue、goto 与 return
开发语言·c++·算法
AI科技星18 分钟前
基于螺旋元逻辑的宇宙统一场论底层公理构建(乖乖数学)
算法·机器学习·数学建模·数据挖掘·量子计算
qiqsevenqiqiqiqi42 分钟前
MC0550鱼肠剑试锋芒
数据结构·算法
仍然.43 分钟前
算法题目---链表
数据结构·算法·链表
luoganttcc1 小时前
华为昇腾(Ascend)等芯片,同样存在“寄存器 / 片上存储资源限制并发”的问题
算法·华为
小O的算法实验室1 小时前
2025年SEVC,神经-粒子群算法+大规模动态优化,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
wayz111 小时前
Day 7:第一周复习与模型综合比较
人工智能·算法·机器学习·量化交易
玛丽莲茼蒿1 小时前
Leetcode hot100 买卖股票的最佳时机【简单】
算法·leetcode·职场和发展
阿Y加油吧1 小时前
两道 LeetCode 题的复盘笔记:从「只会暴力」到「懂优化」
笔记·算法·leetcode