From 5a5390dec5c66369c3db31c05866c2514d6d09c8 Mon Sep 17 00:00:00 2001 From: kunal0411 <114978602+kunal0411@users.noreply.github.com> Date: Wed, 5 Oct 2022 18:26:18 +0530 Subject: [PATCH] Create LCS.cpp --- Data Structure And Algorithms/LCS.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Data Structure And Algorithms/LCS.cpp diff --git a/Data Structure And Algorithms/LCS.cpp b/Data Structure And Algorithms/LCS.cpp new file mode 100644 index 0000000..fac72a7 --- /dev/null +++ b/Data Structure And Algorithms/LCS.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; +class Solution { + public: + int longestCommonSubsequence(string s, string x) { + int n = s.size(); + int m = x.size(); + if(!n || !m) return 0; + s = " " + s; + x = " " + x; + int ret = 0; + vector < vector > dp(n + 1, vector (m + 1)); + for(int i = 1; i <= n; i++){ + for(int j = 1; j <= m ; j++){ + dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]); + if(s[i] == x[j]) { + dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j - 1]); + } + } + } + return dp[n][m]; + } +}; +main(){ + Solution ob; + cout << (ob.longestCommonSubsequence("abcde", "ace")); +}