POJ 1548 (最长公共子串)

来源:互联网 发布:如何投诉淘宝店铺客服 编辑:程序博客网 时间:2024/06/01 07:20

http://poj.org/problem?id=1458

题意:求出两个字符串的最长公共子串,子串可以不是连续的,


思路:可以用一个二维数组保存s1[ i ] 和s2[ j ]之前的最长子串长度(包括s1[ i ] 和s2[ j ])。

那么其实问题显而易见的分成了两种情况s1[ i ] 和s2[ j ]相等和不相等问题自然迎刃而解了。

dp的思想,分成子问题来优化。



#include<iostream>#include<cstring>#include<cstdio>#define M 1000using namespace std;char sz1[M+10],sz2[M+10];int aMaxLen[M+10][M+10];int main(){//    freopen("in.txt","r",stdin);    while(scanf("%s%s",sz1+1,sz2+1) != EOF){        int nLength1 = strlen(sz1+1);        int nLength2 = strlen(sz2+1);        int i,j;        for(i = 0;i <= nLength1; i++)            aMaxLen[i][0] = 0;        for(j = 0;j <= nLength2; j++)            aMaxLen[0][j] = 0;        for(int i = 1;i <= nLength1; i++)            for(int j = 1;j <= nLength2; j++)                if(sz1[i] == sz2[j])                    aMaxLen[i][j] = aMaxLen[i-1][j-1] + 1;                else{                    int nlen1 = aMaxLen[i-1][j];                    int nlen2 = aMaxLen[i][j-1];                    if(nlen1 > nlen2)                        aMaxLen[i][j] = nlen1;                    else                        aMaxLen[i][j] = nlen2;                }        printf("%d\n",aMaxLen[nLength1][nLength2]);    }    return 0;}


0 0
原创粉丝点击