-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCS.cpp
More file actions
96 lines (67 loc) · 1.77 KB
/
LCS.cpp
File metadata and controls
96 lines (67 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//
// Created by mi on 5/25/17.
//
#include <string>
#include <vector>
#include <iostream>
using namespace std;
// 最长公共子序列
void print_LCS(vector<vector<int>> LCS, string A, string B,int i ,int j ) {
int len_A = A.size();
int len_B = B.size();
// for (int i = len_A; i > 0; i--) {
// for (int j = len_B; j > 0; j--) {
if (A[i - 1] == B[j - 1]) {
cout << A[i] << endl;
i--;
j--;
} else {
if (LCS[i][j - 1] > LCS[j - 1][i]) {
j--;
} else {
i--;
}
}
print_LCS(LCS,A,B,i,j);
// }
// }
}
void scan_vector(vector<vector<int>> A) {
int m = A.size();
int n = A[0].size();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cout << A[i][j] << "\t";
}
cout << endl;
}
}
int LCS(string A, string B) {
if (A.empty()) return 0;
if (B.empty()) return 0;
int len_A = A.size();
int len_B = B.size();
vector<vector<int>> LCS = vector<vector<int>>(1 + len_A, vector<int>(1 + len_B));
for (int i = 1; i < 1 + len_A; i++) {
for (int j = 1; j < 1 + len_B; j++) {
if (A[i - 1] == B[j - 1]) {
LCS[i][j] = LCS[i - 1][j - 1] + 1;
} else {
LCS[i][j] = max(LCS[i - 1][j], LCS[i][j - 1]);
}
}
}
//scan vector
scan_vector(LCS);
cout << "===================" << endl;
//print longest common subsequence
print_LCS(LCS, A, B,1+len_A,1+len_B);
return LCS[len_A][len_B];
}
/*
int main() {
string A = "guahaoc";
string B = "guohao";
int lcs_length = LCS(A, B);
cout << lcs_length << std::endl;
}*/