From dbdcf3dbc9fd469cda393f404f39c2ac2e9bcda1 Mon Sep 17 00:00:00 2001 From: Aryan Date: Thu, 14 Oct 2021 17:11:07 +0530 Subject: [PATCH] Added All The File Of Longest Common Subsequence --- LongestCommonSubsequence.cpp | 38 ++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 LongestCommonSubsequence.cpp diff --git a/LongestCommonSubsequence.cpp b/LongestCommonSubsequence.cpp new file mode 100644 index 0000000..6b6a574 --- /dev/null +++ b/LongestCommonSubsequence.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +using namespace std; + +//finding max value +int max(int a, int b) +{ + return (a > b) ? a : b; +} + +//finding LCS +int LongestCommonSubsequence(char *str1, char *str2, int x, int y) +{ + if (x == 0 || y == 0) + { + return 0; + } + if (str1[x - 1] == str2[y - 1]) + { + return (1 + LongestCommonSubsequence(str1, str2, x - 1, y - 1)); + } + else + { + return max(LongestCommonSubsequence(str1, str2, x, y - 1), LongestCommonSubsequence(str1, str2, x - 1, y)); + } +} + +//main function +int main() +{ + char str1[] = "cantonment"; + char str2[] = "longatone"; + int x = strlen(str1); + int y = strlen(str2); + cout << "\nLength of Longest Common Subsequence From Both The Strings Is " << LongestCommonSubsequence(str1, str2, x, y) << endl; + return 0; +} \ No newline at end of file