diff --git a/src/algorithms/dynamic_programming/lcs.h b/src/algorithms/dynamic_programming/lcs.h new file mode 100644 index 00000000..23687e45 --- /dev/null +++ b/src/algorithms/dynamic_programming/lcs.h @@ -0,0 +1,46 @@ +#ifndef LCS_H +#define LCS_H + +#ifdef __cplusplus +#include +#include +#endif + +int lcs(std::string a, std::string b) { + int m = a.length(), n = b.length(); + int res[m + 1][n + 1]; + int trace[20][20]; + + for (int i = 0; i < m + 1; i++) { + for (int j = 0; j < n + 1; j++) { + res[i][j] = 0; + trace[i][j] = 0; + } + } + + for (int i = 0; i < m + 1; ++i) { + for (int j = 0; j < n + 1; ++j) { + if (i == 0 || j == 0) { + res[i][j] = 0; + trace[i][j] = 0; + } + + else if (a[i - 1] == b[j - 1]) { + res[i][j] = 1 + res[i - 1][j - 1]; + trace[i][j] = 1; + + } else { + if (res[i - 1][j] > res[i][j - 1]) { + res[i][j] = res[i - 1][j]; + trace[i][j] = 2; + } else { + res[i][j] = res[i][j - 1]; + trace[i][j] = 3; + } + } + } + } + return res[m][n]; +} + +#endif \ No newline at end of file diff --git a/tests/algorithms/dynamic_programming/lcs.cc b/tests/algorithms/dynamic_programming/lcs.cc new file mode 100644 index 00000000..6d4722f6 --- /dev/null +++ b/tests/algorithms/dynamic_programming/lcs.cc @@ -0,0 +1,11 @@ +#define CATCH_CONFIG_MAIN +#include "../../../src/algorithms/dynamic_programming/lcs.h" +#include "../../catch2/catch.hpp" + +TEST_CASE("testing longest common subsequence") { + std::string a = "AGGTAB", b = "GXTXAYB"; + REQUIRE(lcs(a, b) == 4); + a = "BD"; + b = "ABCD"; + REQUIRE(lcs(a, b) == 2); +} \ No newline at end of file