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