题干:

描述

 

编写一个程序,求两个字符串的最长公共子串。输出两个字符串的长度,输出他们的最长公共子串及子串长度。如果有多个最长公共子串请输出在第一个字符串中先出现的那一个。

特别注意公共子串中可能包含有空格,但不计回车符!

输入

两个字符串,回车结尾,每个字符串中都可能含有空格(每个字符串的长度不超过200个字符)

输出

一共有四行,前两行以Length of String1:和Length of String2:开始冒号后面分别输出两字符串的长度。 第三行Maxsubstring:输出符合题目里描述的子串。第四行是Length of Maxsubstring:加子串长度。注意!冒号后面不要输出多余的空格!

输入样例 1 

this is a string
my string is abc

输出样例 1

Length of String1:16
Length of String2:16
Maxsubstring: string
Length of Maxsubstring:7

输入样例 2 

abcdef
defabc

输出样例 2

Length of String1:6
Length of String2:6
Maxsubstring:abc
Length of Maxsubstring:3

输入样例 3 

aabbcc
aabbcc

输出样例 3

Length of String1:6
Length of String2:6
Maxsubstring:aabbcc
Length of Maxsubstring:6

来源

QDU

 

解题报告:

    刚开始写成了最长公共子序列了、、、对于从0开始读入的字符串问题(即cin>>s而非cin>>s+1),还调试了老半天。。结果发现题目要求公共子序列。。。数据量不大才两百个字符,果断从高往低枚举就好了。。。如果字符数多了可以二分加速一下。、

AC代码:

#include<cstdio>
#include<queue>
#include<string>
#include<cstring>
#include<cmath>
#include<map>
#include<iostream>
#include<algorithm>
#define ll long long
const ll mod = 1e9+7;
using namespace std;
char s1[5005],s2[5005],tmp[5005];
//string s1,s2;
int dp[5500][5500];
int main()
{
	cin.getline(s1+1,1004);
	cin.getline(s2+1,1004);
	int len1 = strlen(s1+1);
	int len2 = strlen(s2+1);
//	if(s1[0] == s2[0]) dp[0][0] = 1,dp[1][0] = 1,dp[0][1] = 1;
//	if(s1[1] == s2[0]) dp[1][0] = 1;
//	if(s1[0] == s2[1]) dp[0][1] = 1;
//	for(int i = 1; i<=len1; i++) {
//		for(int j = 1; j<=len2; j++) {
//			if(s1[i] == s2[j]) dp[i][j] = dp[i-1][j-1]+1;
//			else dp[i][j] = max(dp[i][j-1],dp[i-1][j]);
//		}
//	}
//	int ans = dp[len1][len2];
	//printf("ans = %d\n",ans);
	int ans,flag = 0;
	for(ans = len1; ans >=0; ans--) {
		for(int i = 1; i<=len1-ans+1; i++) {
			for(int j = 0; j<ans; j++) tmp[j] = s1[i+j];
			tmp[ans] = '\0';
			//printf("tmp=%s\n",tmp);
			if(strstr(s2+1,tmp) != NULL) {
				flag = 1;
				break;
			}
		}
		if(flag) break;
	}
	printf("Length of String1:%d\n",len1);
	printf("Length of String2:%d\n",len2);
	printf("Maxsubstring:%s\n",tmp);
	printf("Length of Maxsubstring:%d\n",ans);
	return 0 ;
}