//最长公共子串的计算
//输入:asdfas werasdfaswer
//输出:6
/*
动态规划原理:
1。 将连个字符串分别以行列组成一个矩阵。
2。若该矩阵的节点对应的字符相同,则该节点值为1。
3。当前字符相同节点的值 = 左上角(d[i-1, j-1])的值 +1,这样当前节点的值就是最大公用子串的长。
(s2) b c d e
(s1)
a 0 0 0 0
b 1 0 0 0
c 0 2 0 0
d 0 0 3 0
结果:只需以行号和最大值为条件即可截取最大子串
*/
#include<iostream>
#include<string>
#include<cctype>
using namespace std;
int lcstr(string s1, string s2)//求公共子串
{
//len_max保存公共子串的最大长度,s1_Lindex保存公共子串最后一个元素的位置
int i,k,len_max=0,s1_Lindex=0;
int len1=0, len2=0;
int **c;
if(s1.empty()|| s2.empty())return -1;//string类判断空串string.empty()
len1 = strlen(s1.c_str());
len2 = strlen(s2.c_str());
c = new int*[sizeof(int*)*len1];//分配指针数组
for(int i=0; i<len1; i++)
{ c[i] = new int [sizeof(int*)*len2];
memset(c[i],0,sizeof(int*)*len2);
}
//初始化完毕
for(i=0;i<len1;i++)
{
for(k=0;k<len2;k++)
{
if(i==0||k==0)
{
if(s1[i] == s2[k]) c[i][k]=1;
else c[i][k]=0;
}
else
{
if(s1[i] == s2[k])
{
c[i][k] =c[i-1][k-1] + 1;
if(len_max<c[i][k])
{
len_max = c[i][k];
s1_Lindex = i;
}
}
}
}
}
for(i=0; i<len1; i++) //释放动态数组
{ delete [] c[i];
}
delete c;
return len_max;
}
int main()
{
string input;
string input1 = "aaa";
string input2 = "bbb";
getline(cin,input);
for(string::size_type ix=0;ix!=input.size();++ix)//把大写字母转换为小写
{
if(input[ix]>= 'A'&&input[ix]<= 'Z')
{input[ix] = tolower(input[ix]);}
else
input[ix] = input[ix];
}
//查找第一个空格,把input分为两个字符串
string::size_type pos =input.find_first_of(" ");
input1 = input.substr(0,pos);
input2 = input.substr(pos+1);
int length = lcstr(input1,input2);
cout << length <<endl;
system("pause");
return 0;
}
【华为oj】oj2011最长公共子串的计算
最新推荐文章于 2019-06-24 18:01:47 发布