题解 | #最长公共子序列(二)#
最长公共子序列(二)
http://www.nowcoder.com/practice/6d29638c85bb4ffd80c020fe244baf11
这题有点难,还要好好琢磨一下。
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
int[][]dp = new int[s1.length() + 1][s2.length() + 1];
for (int i = 0; i < s1.length(); i ++) {
for (int j = 0; j < s2.length(); j++) {
if (s1.charAt(i) == s2.charAt(j)) {
dp[i + 1][j + 1] = dp[i][j] + 1;
} else {
dp[i + 1][j + 1] = Math.max(dp[i][j + 1], dp[i + 1][j]);
}
}
}
StringBuilder result = new StringBuilder();
int i = s1.length(), j = s2.length();
while(i != 0 && j != 0) {
if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
result.append(s1.charAt(i - 1));
j--;
i--;
} else if (dp[i - 1][j] > dp[i][j - 1]) {
i--;
} else {
j--;
}
}
if (result.length() == 0) {
return "-1";
}
System.out.print(result);
return result.reverse().toString();
}
}