简单dp -- Common Subsequence POJ - 1458

Common Subsequence POJ - 1458

题意:
给你s, t两个字符串,求出两个字符串的最长公共子串,子串的原串字符按原串顺序组成的。

思路:
dp[i][j]记录s串第i个字符匹配到t串第j个字符的最长公共子串长度,把s串的字符与t串的字符挨个比较,若s[i] == t[j], 则此时匹配的最长字串为dp[i][j] = dp[i - 1][j - 1] + 1,否则dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])。

code:




#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 1e3 + 5;
char s[maxn], t[maxn];
int dp[maxn][maxn];

void init(){
	memset(dp, 0, sizeof(dp));
}

int main(){
	while(cin >> s + 1 >> t + 1){  
	
	   init();

	   int len1 = strlen(s + 1);
	   int len2 = strlen(t + 1);
	   for(int i = 1; i <= len1; i++)
	      for(int j = 1; j <= len2; j++)
	         if(s[i] == t[j]) dp[i][j] =  dp[i - 1][j - 1] + 1;
	         else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
	   
	   
	       
		cout << dp[len1][len2] << endl; 
		
	}
} 
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页