HDU 1159 Common Subsequence

来源:互联网 发布:淘宝主图ps无缝拼接 编辑:程序博客网 时间:2024/06/02 04:32

原题链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1159

题目大意:

给你两个字符串。找出他们的最大公共字串

思路:

逐个匹配。并用DP数组记录下。到这个位置最多有多少个字符匹配
具体想法看代码注释

代码如下:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;char str1[500],str2[500];//用来存放两个字串int dp[500][500];int main(){    while( scanf("%s %s",str1,str2) != EOF )    {        int len1 = strlen( str1 );        int len2 = strlen( str2 );        int i,j;        //补齐空行,便于后面的代码操作        //第一个串竖放,第二个串横放        for( i = 0; i <= len1; i++ )            dp[i][0] = 0;        for( j = 0; j <= len2; j++ )            dp[0][j] = 0;        //逐个匹配        for( i = 0; i < len1; i++ )            for( j = 0; j < len2; j++ )            {                //如果当前项匹配。那么就把前一项已经匹配好的最大值+1赋值给当前的DP就可以了                if( str1[i] == str2[j] )                    dp[i+1][j+1] = dp[i][j] + 1;                //如果不匹配。那么这个位置DP的值就为。从(第一个串)i位置开始匹配到的个数多,还是(第二个串)j位置在之前的位置匹配的多                else                    dp[i+1][j+1] = max( dp[i+1][j],dp[i][j+1] );            }        printf("%d\n",dp[len1][len2]);    }    return 0;}
0 0
原创粉丝点击