最大公共子序列和最大公共子串

发布 : 2020-11-15 分类 : 算法 浏览 :

最大公共子序列

最大公共子串

动态规划(未优化)

动态规划(一级空间优化)

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
#include <iostream>
#include <cstdio>
#include <string.h>
#include <algorithm>
using namespace std;

char s1[1000001], s2[1000001];
int dp[2][1000005];

int lcs() {
int len1 = strlen(s1), len2 = strlen(s2);
int i, j, cur = 1, pre = 0, cnt = 0;
if(len2 > len1) {
for(i = 0; i <= len2; i++) dp[0][i] = 0;
dp[1][0] = 0;
for(i = 1; i <= len1; i++) {
for(j = 1; j <= len2; j++) {
if(s1[i - 1] == s2[j - 1]) {
dp[cur][j] = dp[pre][j - 1] + 1;
cnt = max(cnt, dp[cur][j]);
}
else dp[cur][j] = 0;
}
swap(cur, pre);
}
return cnt;
}
else {
for(i = 0; i <= len1; i++) dp[0][i] = 0;
dp[1][0] = 0;
for(i = 1; i <= len2; i++) {
for(j = 1; j <= len1; j++) {
if(s2[i - 1] == s1[j - 1]) {
dp[cur][j] = dp[pre][j - 1] + 1;
cnt = max(cnt, dp[cur][j]);
}
else dp[cur][j] = 0;
}
swap(cur, pre);
}
return cnt;
}
}

int main() {
while(~scanf("%s%s", s1, s2)) {
int ans = lcs();
printf("%d\n", ans);
}
return 0;
}

动态规划(二级空间优化)

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
#include <iostream>
#include <cstdio>
#include <string.h>
#include <algorithm>
using namespace std;

char s1[1000001], s2[1000001];
int dp[1000001];

int lcs() {
int len1 = strlen(s1), len2 = strlen(s2);
int i, j, tmp, old, cnt = 0;
if(len2 > len1) {
for(i = 0; i <= len2; i++) dp[i] = 0;
for(i = 1; i <= len1; i++) {
old = dp[0];
for(j = 1; j <= len2; j++) {
tmp = dp[j];
if(s1[i - 1] == s2[j - 1]) {
dp[j] = old + 1;
cnt = max(cnt, dp[j]);
}
else dp[j] = 0;
old = tmp;
}
}
return cnt;
}
else {
for(i = 0; i <= len1; i++) dp[i] = 0;
for(i = 1; i <= len2; i++) {
old = dp[0];
for(j = 1; j <= len1; j++) {
tmp = dp[j];
if(s2[i - 1] == s1[j - 1]) {
dp[j] = old + 1;
cnt = max(cnt, dp[j]);
}
else dp[j] = 0;
old = tmp;
}
}
return cnt;
}
}

int main() {
while(~scanf("%s%s", s1, s2)) {
int ans = lcs();
printf("%d\n", ans);
}
return 0;
}
本文作者 : preccrep
原文链接 : https://preccrep.github.io/2020/11/15/%E6%9C%80%E5%A4%A7%E5%85%AC%E5%85%B1%E5%AD%90%E5%BA%8F%E5%88%97%E5%92%8C%E6%9C%80%E5%A4%A7%E5%85%AC%E5%85%B1%E5%AD%90%E4%B8%B2/
版权声明 : 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!
留下足迹

博客已萌萌哒运行(●'◡'●)ノ♥
Theme - BMW | Made With 💗 | Powered by GodBMW