d1i2p3a4k5

knutt morris pratt O(m+n)

Aug 18th, 2016
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.27 KB | None | 0 0
  1. import java.util.*;
  2. class kmp
  3. {
  4.     static Scanner t = new Scanner(System.in);
  5.     public static int[] substring(char pattern[])
  6.     {
  7.         int lps[] = new int[pattern.length];
  8.         lps[0] = 0;
  9.         int j=0;
  10.         int i;
  11.         for(i =1;i<pattern.length;)
  12.         {
  13.             if(pattern[i]==pattern[j])
  14.             {
  15.                 lps[i] = j+1;
  16.                 i++;
  17.                 j++;
  18.             }
  19.             else
  20.             {
  21.                 if(j!=0)
  22.                     j = lps[j-1];
  23.                 else
  24.                 {
  25.                     lps[i]=0;
  26.                     i++;
  27.                 }
  28.             }
  29.         }
  30.         return lps;
  31.     }
  32.  
  33.     public static int kmp(char text[],char pattern[])
  34.     {
  35.             int lps[] = substring(pattern);
  36.             for(int i=0;i<lps.length;i++)
  37.                 System.out.println(lps[i]+" ");
  38.             int j=0,i,k=-1;
  39.             for(i=0;i<text.length&&j<pattern.length;)
  40.             {
  41.                 if(j==0)
  42.                     k=i;
  43.                 if(pattern[j]==text[i])
  44.                 {
  45.                     i++;
  46.                     j++;
  47.                 }
  48.                 else
  49.                 {
  50.                     if(j!=0)
  51.                         j=lps[j-1];
  52.                     else i++;
  53.                 }
  54.             }
  55.             if(j==pattern.length)
  56.                 return i-j+1;
  57.             return -1;
  58.     }
  59.     public static void main(String args[])
  60.     {
  61.         System.out.println("Enter text\t");
  62.         String text = t.nextLine();
  63.         System.out.println("Enter pattern\t");
  64.         String pattern  = t.nextLine();
  65.         int t =  kmp(text.toCharArray(),pattern.toCharArray());
  66.         if(t!=-1)
  67.             System.out.println("pattern found at "+t);
  68.         else System.out.println("pattern not found");
  69.     }
  70. }
Add Comment
Please, Sign In to add comment