From 88b48a12ab2a1bcd953e1d6b0209e7c19664ac30 Mon Sep 17 00:00:00 2001 From: Asif Ahmad <67323237+apexx77@users.noreply.github.com> Date: Thu, 21 Oct 2021 20:04:46 +0530 Subject: [PATCH] Created longest_common_subsequence.cpp --- CPP/longest_common_subsequence.cpp | 38 ++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 CPP/longest_common_subsequence.cpp diff --git a/CPP/longest_common_subsequence.cpp b/CPP/longest_common_subsequence.cpp new file mode 100644 index 0000000..11c76ff --- /dev/null +++ b/CPP/longest_common_subsequence.cpp @@ -0,0 +1,38 @@ +// Problem Statement : Given two strings, find the longest common subsequence + +#include +const int mod = 1e9 + 7; +using namespace std; + +// Function to find LCS + +int lcs(int x, int y, string s1, string s2) { + int dp[x + 1][y + 1]; + memset(dp, -1, sizeof(dp)); + for (int i = 0; i <= x; i++) { + for (int j = 0; j <= y; j++) { + if (i == 0 || j == 0) dp[i][j] = 0; + else { + if (s1[i - 1] == s2[j - 1]) { + dp[i][j] = 1 + dp[i - 1][j - 1]; + } + else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); + } + } + } return dp[x][y]; +} + +// Main function + +int main() { + + int n, k, x, y; + cout << "Enter the lengths of strings : " << "\n"; + cin >> x >> y; + string s1, s2; + cout << "Enter the strings : " << "\n"; + cin >> s1 >> s2; + cout << "The length of longest commmon subsequence is : " << lcs(x, y, s1, s2) << endl; + + return 0; +}