Coincidence(最长公共子序列)

题目描述:
Find a longest common subsequence of two strings.
输入:
First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.
输出:
For each case, output k – the length of a longest common subsequence in one line.
样例输入:
abcd
cxbydz
样例输出:
2
提示:
本题题意很明显就是求两个字符串的最长公共子序列,两个字符串S1和S2,第S1[x] 与 S2[y]的最长公共子序列d[x][y],如果S1[x] == S2[y],那么很明显,d[x][y] = d[x - 1][y - 1] + 1;如果S1[x] != S2[y] 那么d[x][y] = max(d[x][y - 1], d[x - 1][y]);
 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 char s1[101];
 5 char s2[101];
 6 int d[101][101];
 7 int main() {
 8     int len1, len2;
 9     while(~scanf("%s%s", s1, s2)){
10         len1 = strlen(s1);
11         len2 = strlen(s2);
12         for(int i = 0; i <= len1; i++)
13             d[i][0] = 0;
14         for(int i = 0; i <= len2; i++)
15             d[0][i] = 0;
16         for(int i = 1; i <= len1; i++){
17             for(int j = 1; j <= len2;j++){
18                 d[i][j] = 0;
19                 if(s1[i - 1] == s2[j - 1])
20                     d[i][j] = d[i - 1][j - 1] + 1;
21                 else
22                     d[i][j] = d[i - 1][j] > d[i][j - 1] ? d[i - 1][j] : d[i][j - 1];
23             }
24         }
25             printf("%d\n",d[len1][len2]);
26     }
27 }

 

posted @ 2013-02-21 16:47  babyron  阅读(197)  评论(0编辑  收藏  举报