串的模式匹配(KMP算法)
KMP算法的核心在于,研究字串(模式串)存在的某种规律,总结出一种模式,使得主串指针不必回溯,而通过这种模式来移动字串指针或滑动字串,从而完成匹配。以下为:next[j]的代码
using System; namespace Review { /// <summary> /// KMP算法next[j]算法 /// </summary> public class KMP { public static void GetNext(string t,int[] next) { int k=-1,j=0; next[0]=-1; while(j<t.Length-1) { if(k==-1||t[j]==t[k]) { j++; k++; next[j]=k; } else { k=next[k]; } } } } }
以下为测试代码:
using System; namespace Review { class Program { public static void Main(string[] args) { string str="abcabca"; int[] patten=new int[str.Length]; KMP.GetNext(str,patten); Console.ReadKey(); } } }