LintCode Longest Common Subsequence

原题链接在这里:http://www.lintcode.com/en/problem/longest-common-subsequence/

题目:

Given two strings, find the longest common subsequence (LCS).

Your code should return the length of LCS.

Clarification
Example

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

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

题解:

DP. 参考http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/

dp[i][j]表示长度为i的str1 和 长度为j的str2 LCS长度.

若是str1.charAt(i-1)  == str2.charAt(j-1) 尾字符相同, dp[i][j] = dp[i-1][j-1]+1.

若是不同dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]).

举例: 1. "AGGTAB" and "GXTXAYB". Last characters match for the strings. So length of LCS can be written as:
L("AGGTAB", "GXTXAYB") = 1 + L("AGGTAB", "GXTXAYB")

2. "ABCDGH" and "AEDFHR". Last characters do not match for the strings. So length of LCS can be written as:
L("ABCDGH","AEDFHR") = MAX ( L("ABCDG", "AEDFHR"), L("ABCDGH", "AEDFH")).

Time Complexity: O(m*n). Space: O(m*n).

AC Java:

 1 public class Solution {
 2     /**
 3      * @param A, B: Two strings.
 4      * @return: The length of longest common subsequence of A and B.
 5      */
 6     public int longestCommonSubsequence(String A, String B) {
 7         if(A == null || B == null){
 8             return 0;
 9         }
10         int m = A.length();
11         int n = B.length();
12         int [][] dp = new int[m+1][n+1];
13         for(int i = 1; i<=m; i++){
14             for(int j = 1; j<=n; j++){
15                 //两个末尾char match, 数目就是dp[i-1][j-1]+1
16                 if(A.charAt(i-1) == B.charAt(j-1)){
17                     dp[i][j] = dp[i-1][j-1]+1;
18                 }else{
19                     dp[i][j] = Math.max(dp[i][j-1],dp[i-1][j]);
20                 }
21             }
22         }
23         return dp[m][n];
24     }
25 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/5349730.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值