最长公共子串长度

转载请注明出处:http://www.cnblogs.com/zhishoumuguinian/p/8377851.html

最长公共子串长度

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <math.h>
 4 #include <cstring>
 5 #include <vector>
 6 using namespace std;
 7 
 8 int main()
 9 {
10     char str1[l005],str2[1005];
11     cin>>str1>>str2;
12     int maxlen[1005][1005];//用来保存str1[i]左侧,str[j]左侧,最大公共字符串长度
13     int len1=strlen(str1), len2 = strlen(str2);
14     for(int i=0; i<len1; i++)//str1[0]左侧和str2[j]没有公共字符串,所以初始化为maxlen[0][i]=0;
15     {
16         maxlen[0][i]=0;
17     }
18     for(int j=0; j<len2; j++)//str2[0]左侧和str1[i]没有公共字符串,所以初始化为maxlen[j][0] = 0;
19     {
20         maxlen[j][0] = 0;
21     }
22     for(int i=1; i<=len1; i++)
23     {
24         for(int j=1; j<=len2; j++)
25         {
26             if(str1[i-1]==str2[j-1])//如果str1[i-1]==str2[j-1],就在原来长度上加一
27             maxlen[i][j]=maxlen[i-1][j-1]+1;
28             else//否则maxlen[i][j]等与上边和前边的较大者。
29             maxlen[i][j]=max(maxlen[i][j-1],maxlen[i-1][j]);
30         }
31     }
32     cout<<maxlen[len1][len2];//maxlen[len1][len2]保存的就是最大公共子串长度。
33     return 0;
34 }

 

posted @ 2018-01-29 16:10  nefuer  阅读(310)  评论(0编辑  收藏  举报