题目描述:
Given two strings, find the longest common substring.
Return the length of it.
Notice
The characters in substring should occur continuously in original string. This is different with subsequence.
Example
Given A = "ABCD"
, B = "CBCE"
, return 2
.
Challenge
题目思路:
O(n x m) time and memory.
这题想到用一个match matrix,去记录每个A[i]和B[j]是否相等。再遍历A和B,当match[i][j]为true的时候,就沿着这一点的右下对角线一直check下去,看相等的char有多少,并记录它的长度为local。取所有这样的local中的最大值就是我们的答案了。
Mycode(AC = 37ms):
class Solution {
public:
/**
* @param A, B: Two string.
* @return: the length of the longest common substring.
*/
int longestCommonSubstring(string &A, string &B) {
// write your code here
if (A.size() == 0 || B.size() == 0) return 0;
vector<vector<bool>> match(A.size(), vector<bool>(B.size(), false));
// get the match matrix, indicating whether
// A[i] == B[j]
for (int i = 0; i < A.size(); i++) {
for (int j = 0; j < B.size(); j++) {
if (A[i] == B[j]) {
match[i][j] = true;
}
}
}
int global = 0, local = 0;
for (int i = 0; i < A.size(); i++) {
for (int j = 0; j < B.size(); j++) {
int tmp_i = i, tmp_j = j;
local = 0;
// check along the 45 degree line
while (tmp_i < A.size() && tmp_j < B.size() && match[tmp_i][tmp_j]) {
local++;
tmp_i++;
tmp_j++;
}
global = max(global, local);
}
}
return global;
}
};