【查找重复代码】
小明负责维护项目下的代码,需要查找出重复代码,用以支撑后续的代码优化,请你帮助小明找出重复的代码。
重复代码查找方法:以字符串形式给定两行代码(字符串长度 1 < length <= 100,由英文字母、数字和空格组成),找出两行代码中的最长公共子串。
注: 如果不存在公共子串,返回空字符串
示例1
输入:
hello123world
hello123abc4
输出:
hello123
示例2
输入:
private_void_method
public_void_method
输出:
_void_method
解题思路:
1. 比较出两个字符串的长短
2. 使用双层for循环截取短字符串,并判断是否为长字符串的子串,并找出其中最长的。没有的话,输出空字符串。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String text1 = sc.nextLine();
String text2 = sc.nextLine();
String minStr = text1.length() <= text2.length() ? text1 : text2;
String maxStr = minStr.equals(text1) ? text2 : text1;
String resStr = "";
for(int i=0; i<minStr.length()-1; i++){
for(int j=i+1; j<=minStr.length(); j++){
String temp = minStr.substring( i, j);
if(maxStr.contains(temp) && temp.length() > resStr.length()){
resStr = temp;
}
}
}
System.out.println(resStr);
}