Jayakrishna14

KMP String Matching Algorithm

Jul 15th, 2025
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. // Given 2 strings A and B, find the number of occurrences of A in B as a substring.
  2.  
  3. // Note:
  4. // Solve using the KMP string matching algorithm. Do not use an inbuilt library
  5.  
  6. import java.io.*;
  7. import java.util.*;
  8.  
  9. public class Main {
  10.  
  11.     public static int[] computeLPS(String A) {
  12.         int n = A.length();
  13.         int[] LPS = new int[n];
  14.  
  15.         for(int i = 1; i < n; i++) {
  16.             int j = LPS[i - 1];
  17.  
  18.             while(j > 0 && A.charAt(i) != A.charAt(j)) {
  19.                 j = LPS[j - 1];
  20.             }
  21.  
  22.             if(A.charAt(i) == A.charAt(j)) {
  23.                 j++;
  24.             }
  25.  
  26.             LPS[i] = j;
  27.         }
  28.  
  29.         return LPS;
  30.     }
  31.  
  32.     public static int KMP(String A, String B) {
  33.         int LPS[] = computeLPS(A);
  34.  
  35.         int n1 = A.length();
  36.         int n2 = B.length();
  37.  
  38.         int res = 0;
  39.         int j = 0;
  40.  
  41.         for(int i = 0; i < n2; i++) {
  42.             while(j > 0 && (j == n1 || A.charAt(j) != B.charAt(i))) {
  43.                 j = LPS[j - 1];
  44.             }
  45.  
  46.             if(A.charAt(j) == B.charAt(i)) {
  47.                 j++;
  48.             }
  49.  
  50.             if(j == n1) res++;
  51.         }
  52.  
  53.         return res;
  54.     }
  55.  
  56.     public static void main(String[] args) {
  57.         Scanner sc = new Scanner(System.in);
  58.         int T = sc.nextInt();
  59.  
  60.         while(T-- > 0) {
  61.             String A = sc.next();
  62.             String B = sc.next();
  63.  
  64.             System.out.println(KMP(A, B));
  65.         }
  66.  
  67.         sc.close();
  68.     }
  69. }
Tags: Java kmp
Advertisement
Add Comment
Please, Sign In to add comment