Java implements the method to find the longest common substring of two strings

  • 2020-04-01 04:28:35
  • OfStack

This article illustrates how to find the longest common substring of two strings in Java. Share with you for your reference, as follows:

This is a topic on huawei OJ. First, if we write code in Java, huawei OJ has the following three rules to follow, otherwise the compilation cannot pass or the use case cannot pass, the rules are as follows:

(1) must not have a package name;
(2) the Main class name can only be Main;
(3) do not output information irrelevant to the result.

Ok, according to the above rules, the code we wrote is as follows (this code is not optimal, it is only used to record the writing rules of Java code on huawei OJ) :


import java.util.Scanner;
public class Main {
 public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);
  Main mainObj = new Main();
  int len = mainObj.getCommonStrLength(sc.next(),sc.next());
  System.out.println(len);
 }
 int getCommonStrLength(String str1, String str2) {
   str1 = str1.toLowerCase(); 
   str2 = str2.toLowerCase(); 
   int len1 = str1.length(); 
   int len2 = str2.length(); 
   String min = null; 
   String max = null; 
   String target = null;
   min = len1 <= len2 ? str1 : str2;
   max = len1 > len2 ? str1 : str2;
   //Outermost: length of the min substring, starting with the maximum length
   for (int i = min.length(); i >= 1; i--) {
    //Traversing the min substring of length I, starting at 0
    for (int j = 0; j <= min.length() - i; j++) { 
     target = min.substring(j, j + i); 
     //Traverse the Max substring of length I to determine whether it is the same as the target substring, starting at 0
     for (int k = 0; k <= max.length() - i; k++) { 
      if (max.substring(k,k + i).equals(target)) { 
       return i; 
      }
     }
    }
   } 
   return 0; 
 }
}

I hope this article has been helpful to you in Java programming.


Related articles: