文章目录
1. 题目描述
1.1. Limit
Time Limit: 1000 ms
Memory Limit: 131072 kB
1.2. Problem Description
计算两个字符串的最大公共字串的长度,字符不区分大小写
1.3. Input
输入两个字符串
1.4. Output
输出一个整数
1.5. Sample Input
asdfas
werasdfaswer
1.6. Sample Output
6
1.8. Source
2. 解读
动态规划。 list[i][j]
表示以str1[i]和str2[j]
结尾的最长公共子串, 递推方程如下。
l i s t [ i ] [ j ] = { l i s t [ i − 1 ] [ j − 1 ] + 1 , ( s t r 1 [ i ] = s t r 2 [ j ] ) 0 , ( s t r 1 [ i ] ≠ s t r 2 [ j ] ) list[i][j] ={\left\{ \begin{aligned} & list[i - 1][j - 1] + 1 & , (str1[i] = str2[j]) \\ & 0 & , (str1[i] \neq str2[j]) \\ \end{aligned}\right. } list[i][j]={list[i−1][j−1]+10,(str1[i]=str2[j]),(str1[i]=str2[j])
3. 代码
#include<iostream>
using namespace std;
const int MAXM = 1e3 + 1;
int main(){
string str1, str2;
cin>>str1>>str2;
int list[MAXM][MAXM] = {{0}};
int maxAns = 0;
for(int i = 1; i <= str1.size(); i++){
for(int j = 1; j <= str2.size(); j++){
if(toupper(str1[i-1])==toupper(str2[j-1])){
// list[i][j]表示以str1[i]和str2[j]结尾的最长公共子串
list[i][j] = list[i - 1][j - 1] + 1;
maxAns = max(maxAns, list[i][j]);
}else{
list[i][j] = 0;
}
}
}
cout<<maxAns<<endl;
}
联系邮箱:curren_wong@163.com
CSDN:https://me.csdn.net/qq_41729780
知乎:https://zhuanlan.zhihu.com/c_1225417532351741952
公众号:复杂网络与机器学习
欢迎关注/转载,有问题欢迎通过邮箱交流。