Longest Common Subsequence

A classic dynamic programming problem. The idea here is to keep an m*n table lcs where lcs[r+1][c+1] holds the length of the longest common subsequence between text1[:c] and text2[:r]. This is an improvement over bruteforce, because when the cth character of text1 is the same as the rth character of text2, we can simply extend whatever longest common subsequence existed up to text1[:c] and text2[:r], rather than recalculating these values.


_24
class Solution {
_24
private:
_24
array<array<int, 1001>, 1001> lcs;
_24
public:
_24
int longestCommonSubsequence(string text1, string text2) {
_24
const int n = text1.length();
_24
const int m = text2.length();
_24
_24
// the lcs between anything and an empty string is 0
_24
for (int r = 0; r < m; ++r) lcs[r][0] = 0;
_24
for (int c = 0; c < n; ++c) lcs[0][c] = 0;
_24
_24
for (int r = 0; r < m; ++r) {
_24
for (int c = 0; c < n; ++c) {
_24
if (text1[c] == text2[r]) {
_24
lcs[r+1][c+1] = lcs[r][c]+1;
_24
} else {
_24
lcs[r+1][c+1] = max(lcs[r+1][c], lcs[r][c+1]);
_24
}
_24
}
_24
}
_24
return lcs[m][n];
_24
}
_24
};

If you found this solution helpful, consider leaving a star!