题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
http://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s1 = in.next();
String s2 = in.next();
boolean flag = s1.length()<=s2.length();
String str1;
String str2;
//确保str1为短的那一个字符串
if(flag){
str1 = s1;
str2 = s2;
}else{
str1 = s2;
str2 = s1;
}
//在str1中从最长的字串开始遍历,看str2中是否包含,若包含则打印,结束循环
outer:
for(int i = str1.length(); i>0; i--){
for(int j = 0; j<str1.length(); j++){
if(j+i<=str1.length()){
if(str2.contains(str1.substring(j,j+i))){
System.out.print(str1.substring(j,j+i));
break outer;
}
}
}
}
}
}