I’m looking at the algorithm on http://en.wikipedia.org/wiki/Longest_common_substring_problem
They use dynamic programming, which gives them a time of O(nm). However, can’t the same time complexity be achieved with a brute force algorithm? I am doing a homework question, to find this algorithm in O(n*m) time, where n and m are the string lengths.
For a string A and string B, I check if A[i] equals any element in B. If it does equal some B[j], then check if A[i + 1] equals to B[j + 1], then if A[i + 2] = in B[i + 2] and so forth until no more match or end of string. If it is the no match case, then continue checking A[i] in B starting from the last element we checked in B. We repeat this process for every A element, while storing the start and end index for the max substring found so far. This algorithm appears to be O(n*m). If I’m not wrong about this, is there any reason why this approach is not used?
Thanks for any help.
If I’m reading your algorithm correctly, then I believe it is wrong.
Let
A = "abac"andB = "ababac". Then, withi = 0, we see that the strings match atj = 0. So we start matching, and fail atj = 3sinceb != c. So we start matching atj = 3, but fail immediately sinceb != a(note that we don’t start atj = 2since we successfully matcheda = athere). We would then conclude the longest substring isaba, which is incorrect.