动态规划(0)-字符串的交错组成,二维表呈现的是,str1,str2 ,aim三个字符串的关系,那么本篇最长公共子串就是只是str1,str2两个字符串的关系。
问题:给定两个字符串,返回两个字符串的最长公共子串。
举例:str1="1AB2345CD",str2="12345EF",返回“2345”
思路:dp[][] 表示 把str1[i]和str2[j] 当作公共子串最后一个字符时,公共子串最大长度。
二维表仍然是 str1 row i 行 dp[i][0]
str2 col j 列 dp[0][j]
步骤:1.得到dp
1.1dp[0][0]=true;
1.2.第一列col dp[i][0]= str1[i]==str2[0]
1.3.第一行row dp[0][j]= str2[i]==str1[0]
1.4.dp[i][j]
1.4.1 相等 前串+1 str1[i]==str2[j] dp[i][j]=dp[i-1][j-1]+1;
1.4.2 不等 为0 str1[i]!=str2[j] dp[i][j]=0;
2.取dp值
3.截取子串
using namespace std;
typedef vector<vector<int>> ivv;
//14:30
//dp 创建的时候 +1
//1.dp[0][0]
//2.dp[i][0] str1[i] == str2[0] i=1 <len
//3.dp[0][j] str1[0] == str2[j] j=1 j<len
//4.dp[i][j]
//4.1 str1[i]==str2[j] dp[i][j]=dp[i-1][j-1]+1;
//4.2 str1[i]!=str2[j] dp[i][j]=0;
ivv getdp(string str1,string str2)
{
int m_imax = str1.size();//row dp[i][0]
int m_jmax = str2.size();//col dp[0][j]
ivv dp(m_imax );// 行 row str1
for (int i = 0; i < m_jmax; i++)
{
dp[i].resize(m_jmax);//列 col str2
}
//1.dp[0][0]
dp[0][0] = true;
//2.dp[i][0]
for (int i = 1; i < m_imax; i++)
{
if (str1[i] == str2[0])
{
dp[i][0] = 1;
}
}
//3.dp[0][j]
for (int j = 1; j < m_jmax; j++)
{
if (str1[0] == str2[j])
{
dp[0][j] = 1;
}
}
//4.dp[i][j]
for (int i = 1; i < m_imax; i++)
{
for (int j = 1; j < m_jmax; j++)
{
if (str1[i] == str2[j])
{
dp[i][j] = dp[i - 1][j - 1] + 1;
}
}
}
return dp;
}
//二维数组求最大值
void dpmax(ivv dp)
{
int m_max = 0;
for (int i = 0; i < dp.size(); i++)
{
for (int j = 0; j < dp[0].size(); j++)
{
if (dp[i][j] > m_max)
{
m_max = dp[i][j];
}
}
}
}
void strArrCommon_main()
{
cout<<"*****strArrCommon_main******"<<endl;
//string str1 = "1AB2345CD";
//string str2 = "12345EF";
string str1 ="abcde" ;
string str2="bebcd";
//1.得到dp
ivv dp = getdp(str1,str2);
for (int i=0;i<dp.size();i++)//dp.size() row
{
for (int j = 0; j < dp[0].size(); j++) //col
{
cout << dp[i][j] << ",";
}
cout<<endl;
}
//2.dp[i][j]中最大值为,字符串个数,i或者j坐标为位置
int m_max = 0;//字符串个数
int m_end = 0;//起始位置
for (int i = 0; i < str1.size(); i++)
{
for (int j = 0; j < str2.size(); j++)
{
if (dp[i][j] > m_max)
{
m_end = i;
m_max = dp[i][j];
}
}
}
//3.str1 或者str2截取子串
string strre;
strre=str1.substr(m_end - m_max + 1, m_end + 1);
cout << strre << endl;
}