第4章 串和数组(2)

KMP算法的C#实现

感谢:http://www.cppblog.com/suiaiguo/archive/2009/07/16/90237.html 

namespace Andersoft.KMP
{
    //KMP算法最不容易理解的是Next函数,Next函数是KMP算法的精髓
    public class KMP
    {
        //a  b a b a b a b c d a b a b a b a b c d e
        //-1 0 0 1 2 3 4 5 6 0 0 1 2 3 4 5 6 7 8 9 10
        //a  b c a b e a b c a b c f
        //-1 0 0 0 1 2 0 1 2 3 4 5 3
        private static int[] Next(string str)
        {
            int[] arr = new int[str.Length];
            arr[0] = -1;
            int i = -1;
            int j = 0;
            while (j < str.Length-1)
            {
                if (i == -1 || str[i] == str[j])
                {
                    i++;
                    j++;
                    arr[j] = i;
                }
                else
                {
                    i = arr[i]; //KMP算法最难理解的地方,如果不匹配,则i回至arr[i]
                }
            }
            return arr;
        }

        /// <summary>
        /// KMP算法
        /// </summary>
        /// <param name="str1">主串</param>
        /// <param name="str2">匹配串</param>
        /// <returns>匹配返回下标索引</returns>
        public static int KMPMethod(string str1, string str2)
        {
            int[] arr = Next(str2);
            int i = 0;
            int j = 0;

            while (i < str1.Length)
            {
                if (str1[i] == str2[j])
                {
                    //如果是str2的最后一个字符,则两串匹配,返回索引
                    if (j == str2.Length - 1)
                    {
                        return i - j;
                    }
                    //如果不是str2的最后一个字符,则继续匹配两串下一个字符
                    else
                    {
                        i++;
                        j++;
                    }
                }
                //如果不匹配则j回至arr[j]处
                else if (j != 0)
                {
                    j = arr[j];
                }
                //如果j回至arr[j]处后仍不匹配,则继续匹配两串的下一个字符
                else
                {
                    i++;
                }
            }
            return -1;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值