-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
added longest common subsequence algo
- Loading branch information
1 parent
ff64a52
commit 7982e36
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} |