Given two strings, find the longest common substring.
Return the length of it.
注意
The characters in substring should occur continiously in original string. This is different with subsequnce.
2-dimension dp
public int longestCommonSubstring(String A, String B) {
int max = 0;
int[][] d = new int[A.length()+1][B.length()+1];
for (int i = 0; i < A.length(); i++) {
for (int j = 0; j < B.length(); j++) {
if (A.charAt(i) == B.charAt(j)) {
d[i+1][j+1] = d[i][j] + 1;
max = Math.max(max, d[i+1][j+1]);
}
}
}
return max;
}
1-dimension dp
public int longestCommonSubstring(String A, String B) {
int max = 0;
int[] d = new int[B.length()+1];
for (int i = 0; i < A.length(); i++) {
for (int j = B.length()-1; j >= 0; j--) {
if (A.charAt(i) == B.charAt(j)) {
d[j+1] = d[j] + 1;
max = Math.max(max, d[j+1]);
} else {
d[j+1] = 0;
}
}
}
return max;
}