c# kmp算法 (边界条件未处理好,有待改正)

王朝c#·作者佚名  2006-01-10
宽屏版  字体: |||超大  

using System;

namespace kmp

{

/// <summary>

/// Summary description for Class1.

/// </summary>

class Class1

{

/// <summary>

/// The main entry point for the application.

/// </summary>

static int[] next=new int[20];

static int count=0;

static int kmp(char[] a, char[] b, int pos)

{

int i=pos, j=0;

int lena=a.Length,lenb=b.Length;

count=0;

while((i<=lena-1)&&(j<=lenb-1))

{

if(a[i]==b[j])

{++i;++j;}

else

{i=i-j+1; j=0;}

count++;

}

if(j>lenb-1)

return i-lenb;

else

return 0;

}

[STAThread]

static void Main(string[] args)

{

//

// TODO: Add code to start application here

//

int pos=0,reval;

Console.WriteLine("input string1");

string s1=Console.ReadLine();

Console.WriteLine("input string2");

string s2=Console.ReadLine();

char[] p1=s1.ToCharArray();

char[] p2=s2.ToCharArray();

Console.WriteLine("lena={0},lenb={1}",p1.Length,p2.Length);

reval=kmp(p1,p2,pos);

Console.WriteLine("====not kmp ====");

Console.WriteLine("value={0},count={1}",reval,count);

get_next(p2,next);

reval=index_kmp(p1,p2,pos);

Console.WriteLine("====this is kmp ====");

Console.WriteLine("value={0},count={1}",reval,count);

get_goodnext(p2,next);

reval=index_kmp(p1,p2,pos);

Console.WriteLine("====this is good kmp ====");

Console.WriteLine("value={0},count={1}",reval,count);

Console.ReadLine();

}

static int index_kmp(char[] a,char[] b, int pos)

{

int i=pos, j=0;

int lena=a.Length,lenb=b.Length;

count=0;

while((i<=lena-1)&&(j<=lenb-1))

{

if(j==0||a[i]==b[j])

{++i;++j;}

else

{j=next[j];}

count++;

}

if(j>lenb-1)

return i-lenb;

else

return 0;

}

static void get_next(char[] a,int[] next)

{

int i=1,j=0;

next[0]=0;

while(i<=a.Length-2)

{

if(j==0||a[i]==a[j])

{++i;++j;next[i]=j;}

else

{j=next[j];}

}

}

static void get_goodnext(char[] a,int[] next)

{

int i=1,j=0;

next[0]=0;

while(i<=a.Length-2)

{

++i;++j;

if(j==0||a[i]==a[j])

{

if(a[i]!=a[j])

{

next[i]=j;

}

else

{

next[i]=next[j];

}

}

else

{j=next[j];}

}

}

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有