- Longest Common Subsequence
Given two strings, find the longest common subsequence (LCS).
Your code should return the length of LCS.
Example
Example 1:
Input: “ABCD” and “EDCA”
Output: 1
Explanation:
LCS is 'A' or 'D' or 'C'
Example 2:
Input: “ABCD” and “EACB”
Output: 2
Explanation:
LCS is "AC"
Clarification
What’s the definition of Longest Common Subsequence?
https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
http://baike.baidu.com/view/2020307.htm
解法1:DP
class Solution {
public
@param A A string
@param B A string
@return The length of longest common subsequence of A and B
int longestCommonSubsequence(string &A, string &B) {
int m = A.size();
int n = B.size();
if (m == 0 || n == 0) return 0;
vector<vector<int>> dp(m, vectorint(n, 0));
for (int i = 0; i < m; ++i) {
if (A[i] == B[0]) {
dp[i][0] = 1;
}
}
for (int i = 0; i < n; ++i) {
if (A[0] == B[i]) {
dp[0][i] = 1;
}
}
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
if (A[i] == B[j]) {
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 - 1][n - 1];
}
};
代码同步在
https://github.com/luqian2017/Algorithm
二刷: 这个算法更好理解。
class Solution {
public:
/**
* @param a: A string
* @param b: A string
* @return: The length of longest common subsequence of A and B
*/
int longestCommonSubsequence(string &a, string &b) {
int lenA = a.size(), lenB = b.size();
vector<vector<int>> dp(lenA + 1, vector<int>(lenB + 1, 0));
for (int i = 1; i <= lenA; i++) {
for (int j = 1; j <= lenB; j++) {
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
if (a[i - 1] == b[j - 1]) {
dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1);
}
}
}
return dp[lenA][lenB];
}
};
加上滚动数组:记得第一维,不管本来是lenA还是lenA+1,滚动数组的维度都是2。
class Solution {
public:
/**
* @param a: A string
* @param b: A string
* @return: The length of longest common subsequence of A and B
*/
int longestCommonSubsequence(string &a, string &b) {
int lenA = a.size(), lenB = b.size();
vector<vector<int>> dp(2, vector<int>(lenB + 1, 0));
for (int i = 1; i <= lenA; i++) {
for (int j = 1; j <= lenB; j++) {
dp[i % 2][j] = max(dp[i % 2][j - 1], dp[(i - 1) % 2][j]);
if (a[i - 1] == b[j - 1]) {
dp[i % 2][j] = max(dp[i % 2][j], dp[(i - 1) % 2][j - 1] + 1);
}
}
}
return dp[lenA % 2][lenB];
}
};