您的位置:首页 > 产品设计 > UI/UE

Lintcode - Longest common subsequence

2015-02-04 13:05 726 查看
Given two strings, find the longest comment subsequence (LCS).

Your code should return the length of LCS.

样例

For "ABCD" and "EDCA", the LCS is "A" (or D or C), return 1
For "ABCD" and "EACB", the LCS is "AC", return 2

2d: 一维矩阵应该做不了,因为d[i+1][j+1] 与 d[i][j+1] d[i+1][j] d[i][j]都有关
public int longestCommonSubsequence(String A, String B) {
int[][] d = new int[A.length()+1][B.length()+1];
for (int i = 0; i < A.length(); i++) {
for (int j = 0; j < B.length(); j++) {
if (A.charAt(i) == B.charAt(j)) {
d[i+1][j+1] = d[i][j]+1;
} else {
d[i+1][j+1] = Math.max(d[i][j+1], d[i+1][j]);
}
}
}
return d[A.length()][B.length()];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: