import java.io.*;
import java.util.*;
class Knuthmories
{
public int KMP(String T,String P)
{
int n=T.length();
int m=P.length();
int f[]=new int[10];
int i=0;
int j=0;
f=failure(P,f);
while (i
{
if (P.charAt(j)==T.charAt(i))
{
if(j==m-1)
return i-m+1;
i++;
j++;
}
else
if(j>0)
j=f[j-1];
else
i++;
}
return -1;
}
public int[] failure(String P,int f[])
{
int i=1;
int m=P.length();
int j=0;
f[0]=0;
while (i
{
if (P.charAt(j)==P.charAt(i))
{
f[i]=j+1;
i++;
j++;
}
else if(j>0)
j=f[j-1];
else
{
f[i]=0;
i++;
}
}
return f;
}
}
class Knuthmoriesdemo
{
public static void main(String args[])throws IOException
{
String t,p;
BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string of your choice");
t=obj.readLine();
System.out.println("Enter the string to be compared");
p=obj.readLine();
Knuthmories b=new Knuthmories();
int pos=b.KMP(t,p);
System.out.println("The position of the string is :"+pos);
}
}
/*OUTPUT
Enter the string of your choice
university
Enter the string to be compared
sity
The position of the string is :6
Process Exit...
*/
0 comments:
Post a Comment