C # KMP algorithm (boundary condition not handled well, pending correction)

Source: Internet
Author: User
Tags count readline
Algorithm | conditions

Using System;

Namespace KMP
{
<summary>
Summary description for Class1.
</summary>
Class Class1
{
<summary>
The main entry point is 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
//
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];}
}
}
}
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.