|
| 1 | +#include <iostream> |
| 2 | +#include <vector> |
| 3 | +#include <string> |
| 4 | + |
| 5 | +using namespace std; |
| 6 | + |
| 7 | +// Function to find the length of the Longest Common Subsequence |
| 8 | +int longestCommonSubsequenceLength(const string& str1, const string& str2) { |
| 9 | + int m = str1.length(); |
| 10 | + int n = str2.length(); |
| 11 | + |
| 12 | + // Create a 2D table to store the length of LCS |
| 13 | + vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); |
| 14 | + |
| 15 | + // Fill the table using DP |
| 16 | + for (int i = 1; i <= m; i++) { |
| 17 | + for (int j = 1; j <= n; j++) { |
| 18 | + if (str1[i - 1] == str2[j - 1]) { |
| 19 | + dp[i][j] = dp[i - 1][j - 1] + 1; |
| 20 | + } else { |
| 21 | + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); |
| 22 | + } |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + return dp[m][n]; |
| 27 | +} |
| 28 | + |
| 29 | +// Function to find the Longest Common Subsequence |
| 30 | +string longestCommonSubsequence(const string& str1, const string& str2) { |
| 31 | + int m = str1.length(); |
| 32 | + int n = str2.length(); |
| 33 | + |
| 34 | + vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); |
| 35 | + |
| 36 | + for (int i = 1; i <= m; i++) { |
| 37 | + for (int j = 1; j <= n; j++) { |
| 38 | + if (str1[i - 1] == str2[j - 1]) { |
| 39 | + dp[i][j] = dp[i - 1][j - 1] + 1; |
| 40 | + } else { |
| 41 | + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + int length = dp[m][n]; |
| 47 | + string lcs(length, ' '); |
| 48 | + |
| 49 | + int i = m, j = n; |
| 50 | + while (i > 0 && j > 0) { |
| 51 | + if (str1[i - 1] == str2[j - 1]) { |
| 52 | + lcs[length - 1] = str1[i - 1]; |
| 53 | + i--; |
| 54 | + j--; |
| 55 | + length--; |
| 56 | + } else if (dp[i - 1][j] > dp[i][j - 1]) { |
| 57 | + i--; |
| 58 | + } else { |
| 59 | + j--; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return lcs; |
| 64 | +} |
| 65 | + |
| 66 | +int main() { |
| 67 | + string str1, str2; |
| 68 | + cout << "Enter the first string: "; |
| 69 | + cin >> str1; |
| 70 | + cout << "Enter the second string: "; |
| 71 | + cin >> str2; |
| 72 | + |
| 73 | + int length = longestCommonSubsequenceLength(str1, str2); |
| 74 | + cout << "Length of Longest Common Subsequence: " << length << endl; |
| 75 | + |
| 76 | + string lcs = longestCommonSubsequence(str1, str2); |
| 77 | + cout << "Longest Common Subsequence: " << lcs << endl; |
| 78 | + |
| 79 | + return 0; |
| 80 | +} |
0 commit comments