最长公共子序列

给定两个字符串,求它们最长公共子序列的长度。

例如:

s = "abcd", t = "becd"

输出3("bcd")

利用动态规划求解

 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <cstring>
 4 #include <iostream>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 char s[102],t[102];
 9 int dp[102][102];
10 
11 int main(int argc, char const *argv[])
12 {
13     //freopen("input.txt","r",stdin);
14     while(scanf("%s %s",s,t) != EOF) {
15         int n = strlen(s);
16         int m = strlen(t);
17         memset(dp, 0, sizeof(dp));
18         for(int i = 0; i < n; i++) { 
19             for(int j = 0; j < m; j++) {
20                 if(s[i] == t[j]) {
21                     dp[i+1][j+1] = dp[i][j] + 1;
22                 }
23                 else {
24                     dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j]);
25                 }
26             }
27         }
28         printf("%d\n",dp[n][m]);
29     }
30     return 0;
31 }

 

posted @ 2016-08-20 09:58  Jason杰  阅读(184)  评论(0编辑  收藏  举报