核心代码:
if (i == 0 || j == 0) {
c[i][j] = 0;
} else if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
c[i][j] = c[i - 1][j - 1] + 1;
result = Math.max(c[i][j], result);
} else {
c[i][j] = 0;
}
public class LCS2 {
public static int lcs(String str1, String str2) {
int result = 0;
int c[][] = new int[str1.length() + 1][str2.length() + 1];
for (int i = 0; i <= str1.length(); i++) {
for (int j = 0; j <= str2.length(); j++) {
if (i == 0 || j == 0) {
c[i][j] = 0;
} else if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
c[i][j] = c[i - 1][j - 1] + 1;
result = Math.max(c[i][j], result);
} else {
c[i][j] = 0;
}
}
}
return result;
}
}