什么是子序列?一个给定的序列的子序列,就是将给定序列中零个或多个元素去掉之后得到的结果。
什么是子串?给定串中任意个连续的字符组成的子序列称为该串的子串。(相对于子序列,子串是连续的)
如abcdef
acd是子序列。
bcd是子串。
最长公共子序列代码:
public static int str(String s1, String s2) {
int len1 = s1.length();
int len2 = s2.length();
if (len1 == 0 || len2 == 0) {
return 0;
}
int[][] num = new int[len1 + 1][len2 + 1];
for (int i = 0; i <= len1; i++) {
num[i][0] = 0;
}
for (int i = 0; i <= len2; i++) {
num[0][i] = 0;
}
for (int i = 1; i <= len1; i++)
for (int j = 1; j <= len2; j++) {
if (s1.charAt(i - 1) == s2.charAt(j - 1))
num[i][j] = num[i - 1][j - 1] + 1;
else
num[i][j] = Math.max(num[i - 1][j], num[i][j - 1]);
}
return num[len1][len2];
}
最长公共子串代码:
public static int str2(String s1, String s2) {
int len1 = s1.length();
int len2 = s2.length();
if (len1 == 0 || len2 == 0) {
return 0;
}
int[][] num = new int[len1 + 1][len2 + 1];
for (int i = 0; i <= len1; i++) {
num[i][0] = 0;
}
for (int i = 0; i <= len2; i++) {
num[0][i] = 0;
}
int res = 0;
for (int i = 1; i <= len1; i++)
for (int j = 1; j <= len2; j++) {
if (s1.charAt(i - 1) == s2.charAt(j - 1))
num[i][j] = num[i - 1][j - 1] + 1;
if (res < num[i][j])
res = num[i][j];
}
return res;
}