write lcs code in c++
- User
write lcs code in c++
- Assistant
Below is an example C++ program that computes the Longest Common Subsequence (LCS) between two strings using dynamic programming:
#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; // Function to compute the LCS and return it as a string. string lcs(const string& X, const string& Y) { int m = X.size(); int n = Y.size(); // Create a DP table with (m+1) x (n+1) dimensions initialized to 0 vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); // Fill the dp table for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { if (X[i - 1] == Y[j - 1]) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); } } } // Reconstruct the LCS from the dp table int index = dp[m][n]; string lcsStr(index, ' '); // Pre-allocate space for LCS result int i = m, j = n; while (i > 0 && j > 0) { if (X[i - 1] == Y[j - 1]) { // If current character from both strings is same, it's part of LCS. lcsStr[--index] = X[i - 1]; i--; j--; } else if (dp[i - 1][j] > dp[i][j - 1]) { i--; } else { j--; } } return lcsStr; } int main() { string s1, s2; cout << "Enter first string: "; getline(cin, s1); cout << "Enter second string: "; getline(cin, s2); string result = lcs(s1, s2); cout << "Longest Common Subsequence is: " << result << endl; return 0; }Explanation
-
DP Table Initialization:
We create a 2D vectordpof size(m+1) x (n+1)(wheremandnare the lengths ofXandYrespectively) and initialize it with zeros. The celldp[i][j]will hold the length of the LCS of the substringsX[0..i-1]andY[0..j-1]. -
Building the Table:
We iterate through each character of the strings. If the characters match, we setdp[i][j] = dp[i-1][j-1] + 1; otherwise, we take the maximum of the left cell (dp[i-1][j]) or the top cell (dp[i][j-1]). -
Reconstructing the LCS:
Starting fromdp[m][n], we trace back to determine the actual LCS string by comparing characters and moving appropriately in the table. -
I/O:
The program reads two input strings from the user and outputs the computed LCS.
You can compile this code with a C++ compiler (like
g++) and run it to compute the LCS for two given strings. -
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.