题解 | #公共子串计算#
公共子串计算
http://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
String str1 = in.next();
String str2 = in.next();
int length1 = str1.length();
int length2 = str2.length();
int max = 0;
for(int i = 0; i < length1; i++){
for(int j = 0; j < length2; j++){
if(str1.charAt(i) == str2.charAt(j)){
max = Math.max(max, checkLongest(str1, str2, i, j));
}
}
}
System.out.println(max);
}
public static int checkLongest(String str1, String str2, int i, int j){
if(i >= str1.length() || j >= str2.length() || str1.charAt(i) != str2.charAt(j)){
return 0;
}
return 1 + checkLongest(str1, str2, i+1, j+1);
}
}