题目描述:小明负责维护项目下的代码,需要查找出重复代码,用以支撑后续的代码优化,请你帮助小明找出重复的代码。重复代码查找方法:以字符串形式给定两行代码(字符串长度 1 < length <= 100,由英文字母、数字和空格组成),找出两行代码中的最长公共子串。注: 如果不存在公共子串,返回空字符串
输入描述:
输入的参数text1, text2分别表示两行代码
输出描述:
输出任一最长公共子串
示例1
输入:
hello123world
hello123abc4
输出:
hello123
说明:
text1 = "hello123world", text2 = "hello123abc4", 最长的公共子串为 "hello123"
示例2
输入:
private_void_method
public_void_method
输出:
_void_method
说明:
text1 = "private_void_method", text2 = "public_void_method", 最长的公共子串为 "_void_method"
示例3
输入:
hiworld
hiweb
输出:
hiw
说明:
text1 = "hiworld", text2 = "hiweb", 最长的公共子串为 "hiw"
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a = in.nextLine();
String b = in.nextLine();
String x = a.length() < b.length() ? a : b;
String y = a.length() > b.length() ? a : b;
String l = "";
for (int i = 0; i < x.length(); i++) {
String substring = x.substring(0, x.length() - i);
if (y.contains(substring)) {
l = substring;
break;
}
}
for (int i = 0; i < x.length(); i++) {
String substring = x.substring(i);
if (y.contains(substring) && l.length() < substring.length()) {
l = substring;
}
}
System.out.println(l);
}
}