问题描述
描述:
计算两个字符串的最大公共子串(Longest Common Substring)的长度,字符不区分大小写。
输入:
输入两个字符串
输出:
输出一个整数
样例输入:
asdfas werasdfaswer
样例输出:
6
解题思路
这里的最大公共字串要求的字串是连续的。求字串的方法和求子序列方法类似:
当str1[i] ==
str2[j]时,子序列长度veca[i][j]
= veca[i - 1][j - 1] + 1;只是当str1[i] != str2[j]时,veca[i][j]长度要为0,而不是max{veca[i
- 1][j], veca[i][j - 1]}。
代码
public class LongestCommonSubString {
public static int getLongestCommonSubString(String str1, String str2){
int[][] subResults = new int[str1.length()+1][str2.length()+1];
int maxLen=0;
int lastIndex = -1;
for (int i=1;i<=str1.length();i++){
for(int j=1; j<=str2.length();j++){
if (str1.charAt(i-1) == str2.charAt(j-1)){
subResults[i][j] = subResults[i-1][j-1]+1;
if (subResults[i][j]>maxLen){
maxLen = subResults[i][j];
lastIndex=i;
}
}else {
subResults[i][j] = 0;
}
}
}
System.out.println(str1.substring(lastIndex-maxLen, lastIndex));
return maxLen;
}
public static void main(String[] args) {
String s1 = "abcde";
String s2 = "bc";
System.out.println(getLongestCommonSubString(s1, s2));
}
}