美团2017校招-最长公共连续子串

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zlb872551601/article/details/77688074
[编程题] 最长公共连续子串

时间限制:1秒

空间限制:32768K

给出两个字符串(可能包含空格),找出其中最长的公共连续子串,输出其长度。 
输入描述:
输入为两行字符串(可能包含空格),长度均小于等于50.


输出描述:
输出为一个整数,表示最长公共连续子串的长度。

输入例子1:
abcde
abgde

输出例子1:
2
 
   
lcstring,是dp的题,
dp[i][j]=dp[i-1][j-1]+1,str1[i]==str2[j],表示以str1[i]和str[2]结尾的字符串的公共子串会是多少
dp[i][j]=0,str1[i]!=str2[j]
 
   
因为lcsequence也是类似的dp方程是:
dp[i][j]=dp[i-1][j-1]+1,str1[i]==str2[j],表示以str1[i]和str[2]结尾的字符串的公共子序列会是多少
dp[i][j]=max(dp[i-1][j],dp[i][j-1]),str1[i]!=str2[j]
下面的程序把lcstring和lcsequence都写了
#include <iostream>
using namespace std;
#include <string>
#include <algorithm>
int dp[52][52] = { 0 };
int solve(string str1, string str2)
{
	int max_lcs = 0;
	for (int i = 0; i < str1.size();i++)
	{
		for (int j = 0; j < str2.size(); j++)
		{
			if (str1[i]==str2[j])
			{
				dp[i + 1][j + 1] = dp[i][j] + 1;
				max_lcs = max(max_lcs, dp[i + 1][j + 1]);
			}
			else
			{
				dp[i + 1][j + 1] = 0;
				max_lcs = max(max_lcs, dp[i + 1][j + 1]);
			}
		}
	}
	//return dp[str1.size()][str2.size()];
	return max_lcs;
}
int main()
{
	string str1, str2;//字符串居然能包含空格,题目又没说,
	//包含字符串的只能用getline
	getline(cin, str1);
	getline(cin, str2);
	//while (cin >> str1 >> str2)
	//{
		int lcs = solve(str1, str2);
		cout << lcs << endl;
		return 0;
	//}
	//return 0;
}

猜你喜欢

转载自blog.csdn.net/zlb872551601/article/details/77688074
今日推荐