• KMP算法--C#版


            static void BuildTable(string subString, ref int[] next)
            {
                if (string.IsNullOrWhiteSpace(subString)) return;
    
                int j = 0, k = -1;
                next[0] = -1;
                while (j < subString.Length - 1)
                {
                    if (-1 == k || subString[j] == subString[k])
                    {
                        j++;
                        k++;
                        next[j] = k;
                    }
                    else
                    {
                        k = next[k];
                    }
                }
            }
    
            /// <summary>
            /// 查找算法
            /// </summary>
            /// <param name="source">要搜索的字符串</param>
            /// <param name="subString">子串</param>
            /// <returns>子串在source字符串中的开始位置</returns>
            static int KmpSearch(string source, string subString)
            {
                if (string.IsNullOrWhiteSpace(source) || string.IsNullOrWhiteSpace(subString))
                    return -1;
                var next = new int[subString.Length];
                for (int k = 0; k < next.Length; k++)
                {
                    next[k] = -1;
                }
                int i = 0, j = 0,sLen = subString.Length;
    
                BuildTable(subString, ref next);
    
                while (i < sLen)
                {
                    if (j == -1 || source[i] == subString[j])
                    {
                        i++;
                        j++;
                    }
                    else
                    {
                        j = next[j];
                    }
    
                    if (j == sLen)
                    {
                        return i - sLen;
                    }
                }
                return -1;
            }
    

    使用

                string source = "我是中和敏式的服务二是到覅维尔维尔34山东富翁234斯蒂芬234234式的服务二";
                string subString = "山东富翁";
    
                int a = KmpSearch(source, subString);
    
                Console.WriteLine(a);
    
  • 相关阅读:
    arc路径例子-磊哥
    使用路径arc-奥运五环
    arc路径-磊哥
    使用路径arc-七彩
    html5- 摘自网友dudu
    使用路径arc
    textBaseline
    html5-磊哥
    【洛谷1345】 [USACO5.4]奶牛的电信(最小割)
    【洛谷1231】 教辅的组成(网络流)
  • 原文地址:https://www.cnblogs.com/rainnight/p/3467394.html
Copyright © 2020-2023  润新知