题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
http://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
public class Main { public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String line1 = in.nextLine();
String line2 = in.nextLine();
String res="";
int len1=line1.length();
int len2 =line2.length();
if (len1>len2){
res = getCommonCount(line2,line1);
}else{
res = getCommonCount(line1,line2);
}
System.out.println(res);
}
}
public static String getCommonCount(String min,String max){
List<String> data = new ArrayList<>();
for (int i = 0;i<min.length();i++){
for (int j = min.length()-1;j>=i;j--){
String sb1 = min.substring(i,j+1);
if (max.contains(sb1)){
data.add(sb1);
}
}
}
data.sort(new Comparator<String>() {
@Override
public int compare(String s, String t1) {
return Integer.compare(t1.length(),s.length());
}
});
return data.get(0);
}
}