Skip to content

LCS (Longest Common Subsequence) #56

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions LCS/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
LCS (Longest Common Subsequence)

See https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
11 changes: 11 additions & 0 deletions LCS/example.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#include <iostream>
#include <string>

extern int lcs(const std::string&, const std::string&);

int main()
{
std::string s1 = "Tsuki ga kirei desu ne";
std::string s2 = "Taiyo ga mabushii desu ne";
std::cout << lcs(s1, s2) << std::endl;
}
21 changes: 21 additions & 0 deletions LCS/lcs.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#include <string>
#include <vector>

int lcs(const std::string& A, const std::string& B)
{
std::vector<std::vector<int>> LCS(A.length() + 1);
for (unsigned int i = 0; i < LCS.size(); i++)
LCS[i].resize(B.length() + 1);

for (unsigned int i = 1; i <= A.length(); i++) {
for (unsigned int j = 1; j <= B.length(); j++) {
if (A[i - 1] == B[j - 1]) {
LCS[i][j] = LCS[i - 1][j - 1] + 1;
}
else {
LCS[i][j] = std::max(LCS[i - 1][j], LCS[i][j - 1])
}
}
}
return LCS[A.length()][B.length()];
}