算法期中练习——1006. 最长公共子串

算法期中练习——1006. 最长公共子串

Description:

给定两个字符串x = x­1x­2…x­n和y = y­1y­2…ym, 请找出x和y的最长公共子串的长度,也就是求出一个最大的k,使得存在下标i和j有x­ix­i+1…x­i+k-1 = yjy­j+1…y­j+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为给出的两个单词,返回值为最长公共子串的长度.

1
2
3
4
5
6
class Solution {
public:
int longestSubstring(string x, string y) {

}
};

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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;
}
};
------本文结束感谢阅读------