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

lintcode-medium-Longest Common Subsequence

2016-03-26 03:08 429 查看
Given two strings, find the longest common subsequence (LCS).

Your code should return the length of LCS.

Example

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

For
"ABCD"
and
"EACB"
, the LCS is
"AC"
, return
2
.

动态规划:

用一个二维int数组表示A中前i个字符和B中前j个字符的LCS

状态转移:

当A的第i - 1个字符和B的第j - 1个字符相等时,dp[i][j] = dp[i - 1][j - 1] + 1

不相等时,选取dp[i - 1][j]和dp[i][j - 1]中较大的作为dp[i][j]的值

public class Solution {
/**
* @param A, B: Two strings.
* @return: The length of longest common subsequence of A and B.
*/
public int longestCommonSubsequence(String A, String B) {
// write your code here

if(A == null || A.length() == 0 || B == null || B.length() == 0)
return 0;

int m = A.length();
int n = B.length();
int[][] dp = new int[m + 1][n + 1];

dp[0][0] = 0;
for(int i = 1; i <= m; i++)
dp[i][0] = 0;

for(int i = 1; i <= n; i++)
dp[0][i] = 0;

for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
if(A.charAt(i - 1) == B.charAt(j - 1))
dp[i][j] = dp[i - 1][j - 1] + 1;
else
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}

return dp[m]
;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: