题目描述:
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
.
这题还是用dp解。用dp[i][j]表示A[0...i-1], B[0...j-1]的LCS长度。那么我们就可以得到dp方程:
1). 如果A[i - 1] == B[i - 1], 那么我们有3种选择:把这两个char算进去,于是长度有dp[i - 1][j - 1] + 1, 不把这两个char算进去,于是长度可以为dp[i - 1][j], dp[i][j - 1],这3中里面取最大值;
2). 如果item 1)不成立,那么我们在这3中选择里取最大:dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]
Mycode (AC = 15ms):
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
if (A.size() == 0 || B.size() == 0) {
return 0;
}
vector<vector<int>> dp(A.size() + 1, vector<int>(B.size() + 1, 0));
// dp[i][j] denote length of LCS for A[0...i - 1] and B[0...j - 1]
for (int i = 1; i <= A.size(); i++) {
for (int j = 1; j <= B.size(); j++) {
if (A[i - 1] == B[j - 1]) {
dp[i][j] = max(dp[i][j - 1], max(dp[i - 1][j - 1] + 1, dp[i - 1][j]));
}
else {
dp[i][j] = max(dp[i][j - 1], max(dp[i - 1][j - 1], dp[i - 1][j]));
}
}
}
return dp[A.size()][B.size()];
}
};