AlgoPlus v0.1.0
Loading...
Searching...
No Matches
lcs.h
1#ifndef LCS_H
2#define LCS_H
3
4#ifdef __cplusplus
5#include <cstdint>
6#include <iostream>
7#include <string>
8#include <vector>
9#endif
10
18int64_t lcs(const std::string a, const std::string b) {
19 int64_t m = a.length(), n = b.length();
20 std::vector<std::vector<int64_t>> res(m + 1, std::vector<int64_t>(n + 1));
21 std::vector<std::vector<int64_t>> trace(20, std::vector<int64_t>(20));
22
23 for (int64_t i = 0; i < m + 1; i++) {
24 for (int64_t j = 0; j < n + 1; j++) {
25 res[i][j] = 0;
26 trace[i][j] = 0;
27 }
28 }
29
30 for (int64_t i = 0; i < m + 1; ++i) {
31 for (int64_t j = 0; j < n + 1; ++j) {
32 if (i == 0 || j == 0) {
33 res[i][j] = 0;
34 trace[i][j] = 0;
35 }
36
37 else if (a[i - 1] == b[j - 1]) {
38 res[i][j] = 1 + res[i - 1][j - 1];
39 trace[i][j] = 1;
40
41 } else {
42 if (res[i - 1][j] > res[i][j - 1]) {
43 res[i][j] = res[i - 1][j];
44 trace[i][j] = 2;
45 } else {
46 res[i][j] = res[i][j - 1];
47 trace[i][j] = 3;
48 }
49 }
50 }
51 }
52 return res[m][n];
53}
54
55#endif