日期:2013-06-17 浏览次数:20659 次
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])
{
&n