Write lcs code in c++
- User
Write lcs code in c++
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Write lcs code in c++
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a C++ code snippet that calculates the Longest Common Subsequence (LCS) between two strings using dynamic programming. This approach efficiently computes both the length and the actual LCS.
#include <iostream>
#include <vector>
#include <string>
// Function to find the length of the LCS
int lcsLength(const std::string& X, const std::string& Y) {
int m = X.size();
int n = Y.size();
// Create a table to store lengths of LCS
std::vector<std::vector<int>> LCS_table(m + 1, std::vector<int>(n + 1, 0));
// Fill the table in a bottom-up manner
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (X[i - 1] == Y[j - 1]) {
LCS_table[i][j] = LCS_table[i - 1][j - 1] + 1;
} else {
LCS_table[i][j] = std::max(LCS_table[i - 1][j], LCS_table[i][j - 1]);
}
}
}
return LCS_table[m][n];
}
// Function to print the actual LCS
std::string lcs(const std::string& X, const std::string& Y) {
int m = X.size();
int n = Y.size();
// Create a table to store lengths of LCS
std::vector<std::vector<int>> LCS_table(m + 1, std::vector<int>(n + 1, 0));
// Fill the table in a bottom-up manner
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (X[i - 1] == Y[j - 1]) {
LCS_table[i][j] = LCS_table[i - 1][j - 1] + 1;
} else {
LCS_table[i][j] = std::max(LCS_table[i - 1][j], LCS_table[i][j - 1]);
}
}
}
// Backtrack to construct the LCS
std::string lcsStr;
int i = m, j = n;
while (i > 0 && j > 0) {
if (X[i - 1] == Y[j - 1]) {
lcsStr.push_back(X[i - 1]);
i--;
j--;
} else if (LCS_table[i - 1][j] > LCS_table[i][j - 1]) {
i--;
} else {
j--;
}
}
// Reverse the string to get the correct order
std::reverse(lcsStr.begin(), lcsStr.end());
return lcsStr;
}
int main() {
std::string X = "ABCDGH";
std::string Y = "AEDFHR";
std::cout << "Length of LCS: " << lcsLength(X, Y) << std::endl;
std::cout << "LCS: " << lcs(X, Y) << std::endl;
return 0;
}
Dynamic Programming Approach: The code uses a 2D table (LCS_table) to store the lengths of the LCS for substrings of X and Y. This table is filled in a bottom-up manner.
Finding LCS Length: The lcsLength function returns the length of the LCS by accessing the bottom-right corner of the LCS_table.
Constructing LCS: The lcs function backtracks through the LCS_table to construct the actual LCS. It starts from the bottom-right corner and moves diagonally up-left when characters match, or up/down based on which cell has a larger value.
Reversing LCS: Since the LCS is constructed in reverse order, it is reversed at the end to get the correct sequence.
This code efficiently computes both the length and the actual LCS between two strings using dynamic programming.