[Huawei 2018 School Recruitment Written Exam] Find the largest common substring of two strings

Topic description:

Given n pairs of strings, find the greatest common substring in each pair.

Input format:

 2 //Indicates that there are 2 groups of
 fsjdfgjs //The first group of
 fdfg  
 jfdslkdfj //The second group

 fjdkdfs  

Output format:

3

3

The problem is very simple to understand, but it is still very complicated to solve the problem in an optimal way. I am afraid that the KMP algorithm will come to mind when you see the common substring. I saw in "The Optimal Solution to the Problem of Algorithms and Data Structures of IT Famous Enterprises" that the time complexity of the solution is O(M*N) and the additional space complexity is O(1).

However, due to the limited time for online programming, the method I implemented is very simple, that is, 1. Find the shorter string, and then take the substrings from it in turn. This is a bit tricky to take the substrings in turn. The longest one should be taken first and then gradually shortened. , which makes it the longest common substring if found; 2. Compare the substring with the longer string in turn, and if it contains, it is the longest common substring

code show as below:

import java.util.Scanner;
public class SecondQuestion {

	public static void main(String[] args) {
		
			Scanner in = new Scanner(System.in);			
			String number = in.nextLine();
			int num = Integer.parseInt(number);
			
			String[] str = new String[num*2];
			for(int i=0; i<num*2; i++){
				str[i] = in.nextLine();
				str[++i] = in.nextLine();
			}
			String[] arr = new String[num];
			int j =0;
			for(int i=0; i<num*2; i++){
				arr[j] = Max(str[i], str[++i]);
				if(arr[j] == null){
					System.out.println(0);
				}else{
					System.out.println(arr[j].length());
				}
				j++;
			}
		}
		// the largest common substring of the two strings
		public static String Max(String s1, String s2) {
			String max = (s1.length() > s2.length()) ? s1 : s2;
			String min = max.equals(s1) ? s2 : s1;
			for (int i = 0; i < min.length(); i++) {
				for (int m=0,n=min.length()-i ; n!=min.length()+1; m++, n++) {
					String sub = min.substring(m, n);
					if (max.contains(sub)) {
						return sub;
					}
			   }
			}
			return null;
		}
}

Result screenshot:


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325496150&siteId=291194637