jasonpogi1669

Find the Largest Common Substring between Two Strings using Java

Apr 8th, 2022
1,063
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.86 KB | None | 0 0
  1. /*
  2.  * This file is for generating sample input data.
  3.  */
  4.  
  5. import java.io.*;
  6. import java.util.*;
  7.  
  8. public class Main {
  9.    
  10.     public static void main(String[] args) {
  11.        
  12.         Scanner in = new Scanner(System.in);
  13.        
  14.         // input
  15.         String a = in.next();
  16.         String b = in.next();
  17.        
  18.         // find the largest common substring between Strings a and b
  19.         int n = a.length(), m = b.length(), sz = 0;
  20.         String commonSubstring = "";
  21.         for(int len = 1; len <= Math.min(n, m); len++) {
  22.             for(int i = 0; i + len <= n; i++) {
  23.                 for(int j = 0; j + len <= m; j++) {
  24.                     if(a.substring(i, i + len).equals(b.substring(j, j + len))) {
  25.                         sz = Math.max(sz, len);
  26.                         commonSubstring = a.substring(i, i + len);
  27.                     }
  28.                 }
  29.             }
  30.         }
  31.        
  32.         // output
  33.         System.out.println("Largest Common Substring: " + commonSubstring);
  34.         System.out.println("String Size: " + sz);
  35.     }
  36.    
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment