题解 | #最长公共子序列-II#
最长公共子序列-II
http://www.nowcoder.com/practice/6d29638c85bb4ffd80c020fe244baf11
如果s1[i]==s2[j], dp[i][j] = dp[i-1][j-1] + 1
如果s1[i]!=s2[j], dp[i][j] = max(dp[i][j-1],dp[i-1][j])
import java.util.*;
public class Solution {
/**
* longest common subsequence
* @param s1 string字符串 the string
* @param s2 string字符串 the string
* @return string字符串
*/
public String LCS (String s1, String s2) {
// write code here
String[][] dp = new String[s1.length()+1][s2.length()+1];
for (int i = 0; i <= s1.length(); i++) {
dp[i][0] = "";
}
for (int i = 0; i <= s2.length(); i++) {
dp[0][i] = "";
}
for (int i = 1; i <= s1.length(); i++) {
for (int j = 1; j <= s2.length(); j++) {
if (s1.charAt(i-1) == s2.charAt(j-1)) {
dp[i][j] = dp[i-1][j-1] + s1.charAt(i-1);
} else {
if (dp[i][j-1].length() > dp[i-1][j].length()) {
dp[i][j] = dp[i][j-1];
} else {
dp[i][j] = dp[i-1][j];
}
}
}
}
if (dp[s1.length()][s2.length()].length() == 0) {
return "-1";
}
return dp[s1.length()][s2.length()];
}
}
