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.
注意:
1. 你只需要提交Solution类的代码,你在本地可以编写main函数测试程序,但不需要提交main函数的代码. 注意不要修改类和函数的名称.
2. 如果使用全局变量或类成员函数,请记得在longestSubstring中初始化,因为测试时,longestSubstring可能在一次程序执行中被反复调用.
Solution:
class Solution { public: int longestSubstring(string x, string y) { int count = 0; for (int i = 0; i < x.length(); i++) { for (int j = 0; j < y.length(); j++) { if (x[i] == y[j]) { int t = 1; while (true) { if (i + t >= x.length()) break; if (j + t >= y.length()) break; if (x[i + t] == y[j + t]) { t++; } else { break; } } if (t > count) count = t; } } } return count; } };