与最长公共子序列区别就是需要连续
直接代码贴贴,需要注意一下代码中arr数组的意义以及打印出最长子串的做法~
public class LongestCommonSubstring{
public static void main(String[] args) {
String a = "MAEEEVAKLEKHLMLLRQEYVKLQKKLAETEKRCALLAAQANKESSSESFISRLLAIVAD ";
String b = "MAEEEVAKLEKHLMLLRQEYVKLQKKLAETEKRCTLLAAQANKENSNESFISRLLAIVAG";
// String a = "xzyzzyx";
//String b = "zxyyzxz";
lcs(a, b);
}
private static void lcs(String a, String b) {
if (a == null || b == null) {
return;
}
char[] charA = a.toCharArray();
char[] charB = b.toCharArray();
int lengthA = charA.length;
int lengthB = charB.length;
//arr数组保存的是以a[i]和b[j]为结尾的公共子字符串的长度
int[][] arr = new int[lengthA + 1][lengthB + 1];//存储有公共子串的最大长度
for (int i = 1; i <= lengthA; i++) {
for (int j = 1; j <= lengthB; j++) {
if (charA[i - 1] == charB[j - 1]) {
arr[i][j] = arr[i - 1][j - 1] + 1;
}
}
}
int maxLength = 0;
int end = 0;
for (int i = 0; i <= lengthA; i ++) {
for (int j = 0; j <= lengthB; j++) {
if (maxLength < arr[i][j]) {
end = i;//标定最后字符的下标
maxLength = arr[i][j];
}
}
}
System.out.println("最大长度为:" + maxLength);
System.out.println("字符串为:" + a.subSequence(end - maxLength, end));
}
}