Advertisement
a_pramanik

naive pattern matching

Mar 9th, 2020
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.31 KB | None | 0 0
  1. public class NaivePatternMatching {
  2.  
  3.     /**
  4.      * @param args the command line arguments
  5.      */
  6.    
  7.     public static int search(String txt, String pat)
  8.     {
  9.         int M = pat.length();
  10.         int N = txt.length();
  11.  
  12.         int index = -1;
  13.         /* A loop to slide pat one by one */
  14.         for (int i = 0; i <= N - M; i++) {
  15.  
  16.             int j;
  17.  
  18.             /* For current index i, check for pattern  
  19.               match */
  20.             for (j = 0; j < M; j++) {
  21.                 if (txt.charAt(i + j) != pat.charAt(j))
  22.                     break;
  23.             }
  24.             if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]
  25.                 index = i;
  26.         }
  27.         return index;
  28.     }
  29.    
  30.     public static void main(String[] args) {
  31.         // TODO code application logic here
  32.         Scanner sc = new Scanner(System.in);
  33.        
  34.         String txt;
  35.         String pat;
  36.        
  37.         System.out.println("Enter the main string: ");
  38.         txt = sc.nextLine();
  39.         System.out.println("Enter the pattern/finding string: ");
  40.         pat = sc.nextLine();
  41.        
  42.         int ans = search(txt, pat);
  43.        
  44.         if(ans==-1)System.out.println("Pattern not found!!");
  45.         else System.out.println("Pattern found at position "+ans+1);
  46.        
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement