码迷,mamicode.com
首页 > 编程语言 > 详细

两个字符串的最长公共子串求法(C++、动态规划)

时间:2017-09-27 00:52:33      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:动态   i++   tle   ret   turn   include   rtl   mes   break   

#include<iostream>
#include<algorithm>
#include<string>
#include<stdlib.h>
#include<cmath>
using namespace std;
int main()
{
string str1, str2;
string shortString, longString;
//cin>>str1>>str2;
str1 = "dabcf";
str2 = "aabe";
if (str1.length() > str2.length())
{
shortString = str2;
longString = str1;
}
else {
shortString = str1;
longString = str2;
}
int longlength = longString.length();
const int shortlength = shortString.length();
int **array = new int*[longlength];
for (int i = 0; i < longlength; i++)
{
array[i] = new int[shortlength];
}
int maxIndex = 0, maxNum = 0;
for (int i = 0; i < shortlength; i++)
{
if (shortString[i] != longString[0])
{
array[0][i] = 0;
cout << "array[0][" << i << "]" << array[0][i] << " ";
}
else {
maxNum = 1;
maxIndex = i;
for (; i < shortlength; i++)
{
array[0][i] = 1;
cout << "array[0][" << i << "]" << array[0][i] << " ";
}
break;
}
}
cout << endl;
for (int i = 0; i < longlength; i++)
{
if (shortString[0] != longString[i])
{
array[i][0] = 0;
cout << "array[" << i << "]" << "[0]" << array[i][0] << " ";
}
else {
/*if (i > maxNum)
{
maxNum = 1;
maxIndex = i;
}*/
for (; i < longlength; i++)
{
array[i][0] = 1;
cout << "array[" << i << "]" << "[0]" << array[i][0] << " ";
}
break;
}
}

for (int i = 1; i < longlength; i++)
{
for (int j = 1; j < shortlength; j++)
{
int maxTemp = 0;
maxTemp = max(array[i - 1][j], array[i][j - 1]);
cout<<"max(array[i - 1][j], array[i][j - 1])" <<i-1<<","<<j<<" "<<array[i -1][j]<<" "<<
i<<","<<j - 1<<array[i][j - 1]<<endl;
cout << maxTemp << endl;
if (shortString.substr(j, maxTemp + 1) == longString.substr(i, maxTemp + 1))
{
cout << shortString.substr(j , maxTemp + 1);
array[i][j] = maxTemp + 1;
if (array[i][j] > maxNum)
{
maxNum = array[i][j];
maxIndex = j;
}
}
else {
array[i][j] = maxTemp;
}
}
}
cout<<"两个字符串的公共子串是:"<<endl;
cout << shortString.substr(maxIndex, maxNum);
//system("pause");
return 0;
}

两个字符串的最长公共子串求法(C++、动态规划)

标签:动态   i++   tle   ret   turn   include   rtl   mes   break   

原文地址:http://www.cnblogs.com/adamhome/p/7599528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!