首页 > 其他 > 详细

Longest Common Subsequence

时间:2017-05-15 23:31:49      阅读:296      评论:0      收藏:0      [点我收藏+]

Problem statement:

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.

Solution:

This is a DP problem for two sequences. Such as 72. Edit Distance and 583. Delete Operation for Two Strings.

The key points is also dp[i][j] means the LCS of first i chars in A and first j char in B, and return dp[m][n]

class Solution {
public:
    /**
     * @param A, B: Two strings.
     * @return: The length of longest common subsequence of A and B.
     */
    int longestCommonSubsequence(string A, string B) {
        // write your code here
        int m = A.size();
        int n = B.size();
        vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (A[i - 1] == B[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);         
                }
            }
        }
        return dp[m][n];
    }
};

 

 

Longest Common Subsequence

原文:http://www.cnblogs.com/wdw828/p/6858799.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!