KMP算法C#实现

时间:2021-02-10 20:01:27
[TestClass]
    public class Kmptest
    {
        [TestMethod]
        public void Go()
        {
            string t = "AABBCBBABBCACCD";
            string s = "BBABBCAC";
            var next = new int[s.Length];
            Kmp(ref next, t, s);
        }

        public int Kmp(ref int[] next, string t, string s)
        {
            int lt = t.Length;
            int ls = s.Length;
            int i = 0, j = 0;
            Get_Next(ref next, s);
            while (i < lt && j < ls)
            {
                if (j == -1 || t[i] == s[j])
                {
                    i++;
                    j++;
                }
                else
                {
                    j = next[j];
                }
            }
            if (j >= ls)
            {
                return i + 1 - ls;
            }
            else
            {
                return -1;
            }
        }
        public void Get_Next(ref int[] next, string s)
        {
            int ls = s.Length;
            int i = 0, j = -1;
            next[0] = -1;
            while (i < ls-1)
            {
                if (j == -1 || s[i] == s[j])
                {
                    j++;
                    i++;
                    if (s[i] == s[j])
                    {
                        next[i] = next[j];
                    }
                    else
                    {
                        next[i] = j;
                    }
                }
                else
                {
                    j = next[j];
                }
            }
        }
    }