文本比较算法Ⅱ——Needleman/Wunsch算法的C++实现【求最长公共子串(不需要连续)】

算法见:http://www.cnblogs.com/grenet/archive/2010/06/03/1750454.html

 

求最长公共子串(不需要连续)

 1 #include <stdio.h>
 2 #include <string>
 3 #define N 100
 4 
 5 
 6 int max(int a, int b, int c){
 7     return (a>b?a:b)>c?(a>b?a:b):c;
 8 }
 9 
10 int needleman(char s1[], char s2[]){
11     int len1 = strlen(s1);
12     int len2 = strlen(s2);
13     int i,j;
14     int count[N][N];
15     for(i=0;i<len1+1;i++){
16         count[i][0] = 0;
17     }
18     for(i=0;i<len2+1;i++){
19         count[0][i] = 0;
20     }
21     for(i=1;i<len1+1;i++){
22         for(j=1;j<len2+1;j++){
23             if(s1[i] == s2[j]){
24                 count[i][j] = count[i-1][j-1]+1;
25             } else {
26                 count[i][j] = max(count[i-1][j-1],count[i][j-1],count[i-1][j]);
27             }
28         }
29     }
30     return count[len1][len2];
31 }
32 
33 int main(){
34     char s1[N];
35     char s2[N];
36     while(scanf("%s%s",s1,s2)!=EOF){
37         int result = needleman(s1,s2);
38         printf("%d\n",result);
39     }
40     return 0;
41 }

 

posted on 2016-08-03 10:56  杠子  阅读(682)  评论(0编辑  收藏  举报

导航