Problem : 给你两个字符串,求最长公共子串,动态规划,不解释,不懂的可以看我另一篇博客 : http://blog.csdn.net/calmei/article/details/25044213
Code :
//
// main.cpp
// Calmeii
// Problem : 动态规划求最长自序列,不解释
// Created by Calmeii on 14-5-5.
// Copyright (c) 2014年 apple. All rights reserved.
//
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define MAXN 1100
char str1[MAXN], str2[MAXN];
int dp[MAXN][MAXN];
int main()
{
while (gets(str1) && gets(str2)) //可能有空格,当心
{
memset(dp, 0, sizeof(dp));
int len1 = (int)strlen(str1), len2 = (int)strlen(str2);
for (int i = 0; i < len1; i++){
for (int j = 0; j < len2; j++){
if (str1[i] == str2[j]){
dp[i+1][j+1] = dp[i][j]+1; //从0开始可用i+1,j+1
}
else{
dp[i+1][j+1] = max(dp[i][j+1],dp[i+1][j]);
}
}
}
printf("%d\n", dp[len1][len2]);
}
return 0;
}