zoukankan      html  css  js  c++  java
  • KMP算法C#实现

    [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];
                    }
                }
            }
        }
  • 相关阅读:
    SpringMVC扩展
    反射机制
    python day9
    python day8
    python day7
    python day6
    python day4
    python day3
    python day2
    python day1
  • 原文地址:https://www.cnblogs.com/liuyu7177/p/7805737.html
Copyright © 2011-2022 走看看