首页 > 编程语言 > 详细

KMP算法

时间:2019-02-13 10:20:49      阅读:185      评论:0      收藏:0      [点我收藏+]
string tString = "ababcabcacbab";
string pString = "abcac";
int[] next = cal_next(pString, new int[pString.Length], pString.Length);
int locationId = KMP(tString, tString.Length, pString, pString.Length, next);
技术分享图片
 public static int[] cal_next(string str, int[] next, int len)
        {
            int i, j;
            next[0] = -1;
            for (i = 1; i < len; i++)
            {
                j = next[i - 1];
                while (str[j + 1] != str[i] && (j >= 0))
                {
                    j = next[j];
                }
                if (str[i] == str[j + 1])
                {
                    next[i] = j + 1;
                }
                else
                {
                    next[i] = -1;
                }
            }
            return next;
        }
View Code
技术分享图片
  public static int KMP(string str, int slen, string ptr, int plen, int[] next)
        {
            int s_i = 0, p_i = 0;
            int count = 0;

            while (s_i < slen && p_i < plen)
            {
                ++count;
                if (str[s_i] == ptr[p_i])
                {
                    s_i++;
                    p_i++;
                }
                else
                {
                    if (p_i == 0)
                    {
                        s_i++;
                    }
                    else
                    {
                        p_i = next[p_i - 1] + 1;
                    }
                }
            }
            Console.WriteLine("数量:" + count);
            return (p_i == plen) ? (s_i - plen) : -1;
        }
View Code

 

KMP算法

原文:https://www.cnblogs.com/tangjiansheng/p/10368136.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!