Problem:
给定两个字符串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.
Code:
// Problem#: 21106
// Submission#: 5206587
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
class Solution {
public:
int longestSubstring(string x, string y) {
int dp[1001][1001] = {0};
int Maxlength = 0;
if (x.size() == 0 || y.size() == 0)
return 0;
for (int i = 0; i < x.size(); i++) {
for (int j = 0; j < y.size(); j++) {
if(x[i] == y[j]) {
if (i != 0 && j != 0) {
dp[i][j] = dp[i-1][j-1] + 1;
}
if (i == 0 || j == 0) {
dp[i][j] = 1;
}
}
else {
dp[i][j] = 0;
}
Maxlength = max(dp[i][j], Maxlength);
}
}
return Maxlength;
}
};