KMP算法是一种改进的字符串匹配算法,由D.E.Knuth,J.H.Morris和V.R.Pratt提出的,因此人们称它为克努特—莫里斯—普拉特操作(简称KMP算法)。KMP算法的核心是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。具体实现就是通过一个next()函数实现,函数本身包含了模式串的局部匹配信息。KMP算法的时间复杂度O(m+n) 。
实现方式就不再这里献丑了,网上很多讲解,此处只是记录下c#实现的代码。
public class KMP { static int[] GetNext(String ps) { char[] p = ps.ToArray(); int[] next = new [p.Length]; next[0] = -1; int j = 0int k = -while (j < p.Length - ) { if (k == -1 || p[j] == p[k]) { next[++j] = ++k; } else { k = next[k]; } } return next; } GetIndex(String ts,String ps) { char[] t = ts.ToArray(); int i = 0; // 主串的位置 模式串的位置 int[] next = GetNext(ps); while (i < t.Length && j < p.Length) { if (j == -1 || t[i] == p[j]) { 当j为-1时,要移动的是i,当然j也要归0 i++; j++; } { i不需要回溯了 i = i - j + 1; j = next[j]; j回到指定位置 } } if (j ==return i - j; } { return -; } } } test void Main(string[] args) { Console.WriteLine( KMP.GetIndex("abcdbcxdbc",dbc")); Console.ReadKey(); }