Lec3-最长公共子序列(子串)
1.递归方法:
//最大子串的递归解法
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int max(int a, int b)
{
return a>b ? a : b;
}
int lcs(char* a, char* b, int i, int j)
{
if (i == 0 || j == 0)
return 0;
if (*(a + i -1) == *(b + j - 1))
return lcs(a, b, i - 1, j - 1) +1;
else
return max(lcs(a,b,i-1,j),lcs(a,b,i,j-1));
}
int main()
{
char a[500],b[500];
int len1,len2;
while (cin>>a>>b)
{
len1 = strlen(a);
len2 = strlen(b);
cout<<lcs(a,b,len1,len2)<<endl;
}
}
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int max(int a, int b)
{
return a>b ? a : b;
}
int lcs(char* a, char* b, int i, int j)
{
if (i == 0 || j == 0)
return 0;
if (*(a + i -1) == *(b + j - 1))
return lcs(a, b, i - 1, j - 1) +1;
else
return max(lcs(a,b,i-1,j),lcs(a,b,i,j-1));
}
int main()
{
char a[500],b[500];
int len1,len2;
while (cin>>a>>b)
{
len1 = strlen(a);
len2 = strlen(b);
cout<<lcs(a,b,len1,len2)<<endl;
}
}
2.迭代方法:
1 //最大子串的迭代解法
2 //非递归,用一个表做记录
3 #include <iostream>
4 #include <cstring>
5 #include <cstdio>
6
7 using namespace std;
8
9 #define MAX 500
10 int main()
11 {
12 char a[MAX],b[MAX];
13 int dp[MAX][MAX];
14 int i,j,len1,len2;
15 while (cin>>a>>b)
16 {
17 len1 = strlen(a);
18 len2 = strlen(b);
19 for(i=0;i<len1;i++) dp[i][0] = 0;
20 for(j=0;j<len2;j++) dp[0][j] = 0;
21
22 for (i=1;i<=len1;i++)
23 {
24 for (j=1;j<=len2;j++)
25 {
26 if (a[i-1]==b[j-1])
27 dp[i][j]=dp[i-1][j-1]+1;
28 else
29 dp[i][j]=dp[i-1][j]>dp[i][j-1]?dp[i-1][j]:dp[i][j-1];
30 }
31 }
32 cout<<dp[len1][len2]<<endl;
33 }
34 }
2 //非递归,用一个表做记录
3 #include <iostream>
4 #include <cstring>
5 #include <cstdio>
6
7 using namespace std;
8
9 #define MAX 500
10 int main()
11 {
12 char a[MAX],b[MAX];
13 int dp[MAX][MAX];
14 int i,j,len1,len2;
15 while (cin>>a>>b)
16 {
17 len1 = strlen(a);
18 len2 = strlen(b);
19 for(i=0;i<len1;i++) dp[i][0] = 0;
20 for(j=0;j<len2;j++) dp[0][j] = 0;
21
22 for (i=1;i<=len1;i++)
23 {
24 for (j=1;j<=len2;j++)
25 {
26 if (a[i-1]==b[j-1])
27 dp[i][j]=dp[i-1][j-1]+1;
28 else
29 dp[i][j]=dp[i-1][j]>dp[i][j-1]?dp[i-1][j]:dp[i][j-1];
30 }
31 }
32 cout<<dp[len1][len2]<<endl;
33 }
34 }
你问我生命中还有什么可追寻?