• cnblogs
• belong

# 2. 求解算法

## 动态规划

• 如果$x_m = y_n$，则$z_k = x_m = y_n$，有$Z_{k-1}$$X_{m-1}$$Y_{n-1}$的LCS；
• 如果$x_m \ne y_n$，则$Z_{k}$$X_{m}$$Y_{n-1}$的LCS，或者是$X_{m-1}$$Y_{n}$的LCS。

### DP求解LCS

$c[i,j] = \left\{ {\matrix{ 0 & {{i = 0 \rm{\ or \ }j = 0}} \cr {c[i - 1,j - 1] + 1} & {{i, j > 0 \rm{\ and\ } \ }{{x}}_i} = {y_j} \cr {\max ({c[i, j - 1], c[i - 1, j])}} & {{i, j > 0 \rm{\ and\ }}{{\rm{x}}_i} \ne {y_j}} \cr } } \right.$

public static int lcs(String str1, String str2) {
int len1 = str1.length();
int len2 = str2.length();
int c[][] = new int[len1+1][len2+1];
for (int i = 0; i <= len1; i++) {
for( int j = 0; j <= len2; 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;
} else {
c[i][j] = max(c[i - 1][j], c[i][j - 1]);
}
}
}
return c[len1][len2];
}


### DP求解最长公共子串

$c[i,j] = \left\{ {\matrix{ 0 & {i = 0 \rm{\ or\ }j = 0} \cr {c[i - 1,j - 1]+1} & {{x_i} = {y_j}} \cr 0 & {{x_i} \ne {y_j}} \cr } } \right.$

public static int lcs(String str1, String str2) {
int len1 = str1.length();
int len2 = str2.length();
int result = 0;     //记录最长公共子串长度
int c[][] = new int[len1+1][len2+1];
for (int i = 0; i <= len1; i++) {
for( int j = 0; j <= len2; 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 = max(c[i][j], result);
} else {
c[i][j] = 0;
}
}
}
return result;
}


# 3. 参考资料

[1] cs2035, Longest Common Subsequence.
[2] 一线码农, 经典算法题每日演练——第四题 最长公共子序列.
[3] GeeksforGeeks, Dynamic Programming | Set 29 (Longest Common Substring).

posted @ 2014-09-10 09:43  Treant  阅读(23339)  评论(2编辑  收藏  举报