Description
给定两个字符串x = x1x2…xn和y = y1y2…ym, 请找出x和y的最长公共子串的长度,也就是求出一个最大的k,使得存在下标i和j有xixi+1…xi+k-1 = yjyj+1…yj+k-1.
x和y只含有小写字母,长度均在1和1000之间.
请为下面的Solution类实现解决上述问题的函数longestSubstring,函数的参数x和y为给出的两个单词,返回值为最长公共子串的长度.
class Solution {
public:
int longestSubstring(string x, string y) {
}
};
例1:x = “abcd”, y = “cdef”,返回值为2.
例2:x = “abcabc”, y = “xyz”,返回值为0.
例3:x = “introduction”, y = “introductive”,返回值为10.
注意:
1. 你只需要提交Solution类的代码,你在本地可以编写main函数测试程序,但不需要提交main函数的代码. 注意不要修改类和函数的名称.
2. 如果使用全局变量或类成员函数,请记得在longestSubstring中初始化,因为测试时,longestSubstring可能在一次程序执行中被反复调用.
解析:
考试时我百度了下算法思路(嘻…嘻嘻嘻…)。然而当时没彻底弄懂这个思想,代码打成了子序列。
最长公共子串(Longest Common Substring)与最长公共子序列(Longest Common Subsequence)的区别: 子串要求在原字符串中是连续的,而子序列则只需保持相对顺序一致,并不要求连续。例如X = {a, Q, 1, 1}; Y = {a, 1, 1, d, f}那么,{a, 1, 1}是X和Y的最长公共子序列,但不是它们的最长公共字串。
参考的博客(很棒,还有输出子序列的代码):
借图~
子序列的转移方程:
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<time.h>
using namespace std;
class Solution {
public:
int longestSubstring(string x, string y) {
if (x == "" || y == "")
return 0;
int sizeX = x.size();
int sizeY = y.size();
vector<vector<int>> matrix(sizeX + 1, vector<int>(sizeY + 1));
for (int i = 0; i < sizeX; ++i)
matrix[i][0] = 0;
for (int j = 0; j < sizeY; ++j)
matrix[0][j] = 0;
for (int i = 1; i <= sizeX; ++i)
{
for (int j = 1; j <= sizeY; ++j)
{
if (x[i - 1] == y[j - 1]) {
matrix[i][j] = matrix[i - 1][j - 1] + 1;
}
else {
matrix[i][j] = max(matrix[i - 1][j], matrix[i][j - 1]);
}
}
}
return matrix[sizeX][sizeY];
}
};
int main() {
Solution solution;
string a = "abcdefg";
string b = "bcdf";
int res = solution.longestSubstring(a, b);
cout << res << endl;
system("pause");
return 0;
}
对于子串,唯一不同之处,只是当x[i] != y[j]时,matrix[i][j]长度要为0,而不是max{matrix[i - 1][j], matrix[i][j - 1]}。最终返回这个矩阵中最大的数字即可。
class Solution {
public:
int longestSubstring(string x, string y) {
if (x == "" || y == "")
return 0;
int sizeX = x.size();
int sizeY = y.size();
vector<vector<int>> matrix(sizeX + 1, vector<int>(sizeY + 1));
for (int i = 0; i < sizeX; ++i)
matrix[i][0] = 0;
for (int j = 0; j < sizeY; ++j)
matrix[0][j] = 0;
for (int i = 1; i <= sizeX; ++i)
{
for (int j = 1; j <= sizeY; ++j)
{
if (x[i - 1] == y[j - 1]) {
matrix[i][j] = matrix[i - 1][j - 1] + 1;
}
else {
matrix[i][j] = 0;
//matrix[i][j] = max(matrix[i - 1][j], matrix[i][j - 1]);
}
}
}
int maxNum = 0;
for (int i = 0; i <= sizeX; i++) {
for (int j = 0; j <= sizeY; j++) {
maxNum = max(maxNum, matrix[i][j]);
}
}
return maxNum;
}
};