您的位置:首页 > 其它

串的模式匹配(KMP算法)

2010-01-13 20:13 197 查看
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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: