forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest-common-substring.cpp
38 lines (33 loc) · 1.12 KB
/
longest-common-substring.cpp
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
// Time: O(m * n)
// Space: O(min(m, n))
class Solution {
public:
/**
* @param A, B: Two string.
* @return: the length of the longest common substring.
*/
int longestCommonSubstring(string &A, string &B) {
if (A.length() < B.length()) {
return longestCommonSubstring(B, A);
}
// table[i][j] means the longest length of common substring
// of A which ends with A[i - 1] and B which ends with B[j - 1].
vector<vector<int>> table(2, vector<int>(A.length() + 1, 0));
int longest = 0;
// if A[i - 1] != B[j - 1]:
// table[i][j] = 0
// if A[i - 1] == B[j - 1]:
// table[i][j] = table[i - 1][j - 1] + 1
for (int i = 1; i < A.length() + 1; ++i) {
for (int j = 1; j < B.length() + 1; ++j) {
if (A[i - 1] != B[j - 1]) {
table[i % 2][j] = 0;
} else {
table[i % 2][j] = table[(i - 1) % 2][j - 1] + 1;
longest = max(longest, table[i % 2][j]);
}
}
}
return longest;
}
};