const char *_longest_common_substr(const char *s1, const char *s2, int n, int m) {
// assert n >= m
int max = 0; // keep track of max length found
int tmp = 0; // value is incremented till letters match
int begin = 0;
int try_begin = 0; // possible new begin index
int end = 0; // rv = s2[begin : end - 1]
for (int i = 0; i < n; i++) {
tmp = 0;
try_begin = 0;
// s1 is scanned circularly
for (int j = 0; j < m; j++) {
int index = (j + i) % n; // current s1 index
if (index < n && s1[index] == s2[j]) {
if (tmp == 0)
try_begin = j;
tmp++;
} else {
tmp = 0;
}
if (tmp > max) {
max = tmp;
begin = try_begin;
end = j + 1;
}
}
}
int size = begin >= end ? 0 : end - begin;
char *rv = malloc((size + 1) * sizeof(*rv));
int i;
for (i = 0; i < size; i++)
rv[i] = s2[begin + i];
rv[i] = '\0';
return rv;
}
const char *longest_common_substr(const char *s1, const char *s2, int n, int m) {
if (n < m)
return _longest_common_substr(s2, s1, m, n);
return _longest_common_substr(s1, s2, n, m);
}
Is this code correct to find longest common substring? I don't understand why in many places, for example wikipedia, they use a matrix to solve the problem, while in this apparently simple solution there is no need for it and time complexity is still O(n*m) while space complexity is O(1). A possible test is
int main() {
const char *str1 = "identification";
const char *str2 = "administration";
printf("%s\n", longest_common_substr(str1, str2, strlen(str1), strlen(str2)));
}
and the output is
ation
substring is intended in a circular way, so with input
action
tionac
the output will be
tionac
anyway i could add two different invalid character at the end of the strings to remove this property