动态规划-最长子字符串

原题:poj-1458

分析:我用二维数组dp[i][j]储存长度分别为i和j的a、b两个字符串最大子字符串的数量。

代码:

#include <iostream>
#include <string.h>
#include <string>
#include <cstdio>    
using namespace std;
const int maxn = 1000;

int dp[maxn][maxn];
string a,b; 

int main()
{
    while( cin>>a>>b ){
        memset(dp,0,sizeof(dp));
        int len1 = a.length();
        int len2 = b.length();
//        for(int i = 1;i <= len1;++i){
//            for(int j = 1;j <= len2;++j){
//                cout << dp[i][j];
//            }
//            cout << endl;
//        }
        for(int i = 1;i <= len1;++i){
            for(int j = 1;j <= len2;++j){
                if( a[i-1]==b[j-1] ) dp[i][j] = dp[i-1][j-1]+1;
                else {
                    dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
                //    dp[i][j] = max(dp[i][j],dp[i-1][j-1]);
                }
            }
        }
        cout << dp[len1][len2] << endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/chenxi0x0/p/9710946.html