题目:
Given two strings, find the longest common subsequence (LCS).
Your code should return the length of LCS.
Clarification
What's the definition of Longest Common Subsequence?
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 1 ()
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) { int n1 = A.size(), n2 = B.size(); vector<vector<int>> dp(n1 + 1, vector<int> (n2 + 1, 0)); for (int i = 1; i <= n1; ++i) { for (int j = 1; j <= n2; ++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[n1][n2]; } };