算法期中练习——1006. 最长公共子串
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之间.
Example:
例1:x = “abcd”, y = “cdef”,返回值为2.
例2:x = “abcabc”, y = “xyz”,返回值为0.
例3:x = “introduction”, y = “introductive”,返回值为10.
请为下面的Solution类实现解决上述问题的函数longestSubstring,函数的参数x和y为给出的两个单词,返回值为最长公共子串的长度.
class Solution {
public:
int longestSubstring(string x, string y) {
}
};
代码如下:
class Solution {
public:
int longestSubstring(string x, string y) {
int a = x.length();
int b = y.length();
int dp[a + 1][b + 1];
int max = 0;
for (int j = 0; j < b; j++) dp[0][j] = 0;
for (int i = 0; i < a; i++) dp[i][0] = 0;
for (int i = 1; i <= a; i++) {
for (int j = 1; j <= b; j++) {
if (x[i-1] == y[j-1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
if (max < dp[i][j]) max = dp[i][j];
}
else {
dp[i][j] = 0;
}
}
}
return max;
}
};
// another solution, but is the same
class Solution {
private:
vector<vector<int>> f;
public:
int longestSubstring(string x, string y) {
int n, m, i, j;
n = x.length();
m = y.length();
f.resize(n + 1);
for (i = 0; i <= n; i++) f[i].resize(m + 1);
int res = 0;
for (i = 0; i <= n; i++) {
for (j = 0; j <= m; j++) {
if (i == 0 || j == 0 || x[i - 1] != y[j - 1]) f[i][j] = 0;
else f[i][j] = f[i - 1][j - 1] + 1;
if (f[i][j] > res) res = f[i][j];
}
}
return res;
}
};