Skip to content

Commit

Permalink
added longest common subsequence algo
Browse files Browse the repository at this point in the history
  • Loading branch information
spirosmaggioros committed Jan 26, 2024
1 parent ff64a52 commit 7982e36
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/algorithms/dynamic_programming/lcs.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#ifndef LCS_H
#define LCS_H

#ifdef __cplusplus
#include <iostream>
#include <string>
#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
11 changes: 11 additions & 0 deletions tests/algorithms/dynamic_programming/lcs.cc
Original file line number Diff line number Diff line change
@@ -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);
}

0 comments on commit 7982e36

Please sign in to comment.