一、最长公共子序列
(一)题目
- 给定两个字符串 text1 和 text2,返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 ,返回 0 。
- 一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
- 例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。
- 两个字符串的 公共子序列 是这两个字符串所共同拥有的子序列。
(二)举例
(三)核心代码
int LCS(int n1, int n2, string t1, string t2,vector<vector<int>>* dp)
{
for (int i = 1; i <= n1; i++)
{
for (int j = 1; j <= n2; j++)
{
if (t1[i-1] == t2[j-1])//两个字母相同
(*dp)[i][j] = ((*dp)[i - 1][j - 1] + 1);
else
(*dp)[i][j] = max((*dp)[i - 1][j], (*dp)[i][j - 1]);
}
}
return (*dp)[n1][n2];
}
(四)完整代码
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int LCS(int n1, int n2, string t1, string t2,vector<vector<int>>* dp)
{
for (int i = 1; i <= n1; i++)
{
for (int j = 1; j <= n2; j++)
{
if (t1[i-1] == t2[j-1])//两个字母相同
(*dp)[i][j] = ((*dp)[i - 1][j - 1] + 1);
else
(*dp)[i][j] = max((*dp)[i - 1][j], (*dp)[i][j - 1]);
}
}
return (*dp)[n1][n2];
}
void print(vector<vector<int>>* dp)//打印
{
for (int i = 1; i <= dp->size()-1; i++)
{
for (int j = 1; j <= dp[0].size()-1; j++)
{
cout << (*dp)[i][j] << " ";
}
cout << endl;
}
}
int main()
{
string text1, text2;
cout << "分别输入字符串1和字符串2:"<<endl;
//getline可以整行读取(包括空格)
getline(cin, text1);
getline(cin, text2);
int n1 = text1.size();//字符串1的长度
int n2 = text2.size();//字符串2的长度
vector<vector<int>>dp(n1 + 1, vector<int>(n2 + 1, 0));
cout << "最长公共子序列=:" << LCS(n1, n2, text1, text2, &dp) << endl;
cout << "网格:" << endl;
print(&dp);
}
二、最长公共子串
(一)定义
- 是两个及以上字符串最长的公共子串,是连续的
(二)举例
(三)核心代码
void LCS(int n1, int n2, string t1, string t2, vector<vector<int>>* dp)
{
for (int i = 1; i <= n1; i++)
{
for (int j = 1; j <= n2; j++)
{
if (t1[i - 1] == t2[j - 1])//两个字母相同
(*dp)[i][j] = ((*dp)[i - 1][j - 1] + 1);
else//两个字母不同
(*dp)[i][j] = 0;
}
}
}
(四)完整代码
#include<iostream>
#include<string>
#include<vector>
using namespace std;
void LCS(int n1, int n2, string t1, string t2, vector<vector<int>>* dp)
{
for (int i = 1; i <= n1; i++)
{
for (int j = 1; j <= n2; j++)
{
if (t1[i - 1] == t2[j - 1])//两个字母相同
(*dp)[i][j] = ((*dp)[i - 1][j - 1] + 1);
else//两个字母不同
(*dp)[i][j] = 0;
}
}
}
void print(vector<vector<int>>* dp)//打印
{
int max = (*dp)[0][0];//找最长公共子串的长度
for (int i = 1; i <= dp->size() - 1; i++)
{
for (int j = 1; j <= dp[0].size() - 1; j++)
{
cout << (*dp)[i][j] << " ";
max = max > (*dp)[i][j] ? max : (*dp)[i][j];
}
cout << endl;
}
cout << "最长公共子串的长度是:" << max << endl;
}
int main()
{
string text1, text2;
cout << "分别输入字符串1和字符串2:" << endl;
//getline可以整行读取(包括空格)
getline(cin, text1);
getline(cin, text2);
int n1 = text1.size();//字符串1的长度
int n2 = text2.size();//字符串2的长度
vector<vector<int>>dp(n1 + 1, vector<int>(n2 + 1, 0));
LCS(n1, n2, text1, text2, &dp);
cout << "网格:" << endl;
print(&dp);
}
//分别输入字符串1和字符串2:
//fish
//hish
//网格:
//0 0 0 0
//0 1 0 0
//0 0 2 0
//1 0 0 3
//最长公共子串的长度是:3