-
Notifications
You must be signed in to change notification settings - Fork 22
/
0065.cpp
48 lines (45 loc) · 1018 Bytes
/
0065.cpp
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
// 0065.查找两个字符串a,b中的最长公共子串
// keywords: 最长公共子串
#include <iostream>
using namespace std;
int lcs(string a, string b)
{
if(a.size() > b.size()) {
string tmp = a;
a = b;
b = tmp;
}
a.insert(0, 1, ' ');
b.insert(0, 1, ' ');
int n = a.size(), m = b.size();
int dp[n][m];
int maxLen = 0, last;
for(int i = 0; i < n; i++) dp[i][0] = 0;
for(int j = 0; j < m; j++) dp[0][j] = 0;
for(int i = 1; i < n; i++)
{
for(int j = 1; j < m; j++)
{
if(a[i] == b[j]) {
dp[i][j] = dp[i-1][j-1] + 1;
if(maxLen < dp[i][j]) {
maxLen = dp[i][j];
last = i;
}
} else {
dp[i][j] = 0;
}
}
}
cout << a.substr(last-maxLen+1, maxLen) << endl;
return maxLen;
}
int main()
{
string a, b;
while(cin >> a >> b)
{
lcs(a, b);
}
return 0;
}