题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
http://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
import java.util.Scanner;
public class Main {
public static void main (String []args){
Scanner sc= new Scanner(System.in);
while(sc.hasNext()){
System.out.println(comStr(sc.nextLine(),sc.nextLine()));
}
sc.close();
}
public static String comStr(String str1,String str2){
String small = str1.length()<str2.length()?str1:str2;
String big = str1.length()<str2.length()?str2:str1;
int len =0;
int []index =new int[2];
for(int i =0; i<small.length();i++){
for(int j = small.length();j>i;j--){
if(big.contains(small.substring(i,j)) && (j-i > len)){
len = j-i;
index[0] = j;
index[1] = i;
break;
}
}
}
return small.substring(index[1],index[0]);
}
}
public class Main {
public static void main (String []args){
Scanner sc= new Scanner(System.in);
while(sc.hasNext()){
System.out.println(comStr(sc.nextLine(),sc.nextLine()));
}
sc.close();
}
public static String comStr(String str1,String str2){
String small = str1.length()<str2.length()?str1:str2;
String big = str1.length()<str2.length()?str2:str1;
int len =0;
int []index =new int[2];
for(int i =0; i<small.length();i++){
for(int j = small.length();j>i;j--){
if(big.contains(small.substring(i,j)) && (j-i > len)){
len = j-i;
index[0] = j;
index[1] = i;
break;
}
}
}
return small.substring(index[1],index[0]);
}
}