diff --git a/LCS/README.md b/LCS/README.md new file mode 100644 index 0000000..e96dcfd --- /dev/null +++ b/LCS/README.md @@ -0,0 +1,3 @@ +LCS (Longest Common Subsequence) + +See https://en.wikipedia.org/wiki/Longest_common_subsequence_problem diff --git a/LCS/example.cpp b/LCS/example.cpp new file mode 100644 index 0000000..bced605 --- /dev/null +++ b/LCS/example.cpp @@ -0,0 +1,11 @@ +#include +#include + +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; +} diff --git a/LCS/lcs.cpp b/LCS/lcs.cpp new file mode 100644 index 0000000..649a2b4 --- /dev/null +++ b/LCS/lcs.cpp @@ -0,0 +1,21 @@ +#include +#include + +int lcs(const std::string& A, const std::string& B) +{ + std::vector> 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()]; +}