4 ms·
The algorithms used in this article are _extremely_ bad for the case! Realize that the guy is just trying to find the _longest overlap_ between two strings. Thi
by kilburn 15y ago
The algorithms used in this article are _extremely_ bad for the case! Realize that the guy is just trying to find the _longest overlap_ between two strings. This is, the longest part at the end of text1 that is repeated exactly at the beggining of text2.
With that in mind, it is _obvious_ that there is an algorithm linear in the size of the overlap to compute it. For instance:
def commonOverlapSanely(text1, text2):
right = len(text1)-1
left = 0
maxleft = len(text2)
while left < maxleft and right >= 0:
if text1[right] != text2[left]:
break
right -= 1
left += 1
return left
Instead of using this _very simple_ algorithm, the author employs three different approaches:
1. A "naive" version that keeps copying increasingly large portions of the original strings, and checking the whole portion each time. This obviously makes the algorithm quadratic in the size of the overlap, thus leading to very bad performance.
2. The KMP algorithm, that is designed to search for occurrences of a string within another one, disregarding where. This is a silly thing to do because the resulting algorithm is linear in the size of the longest input string, instead of on the size of the actual overlap.
3. An "indexOf" monstruosity, that is so wrong it is even hard to explain. Carefuly inspect the code and cry.
Now, please tell me if I missed something...
- deleted 15y ago[deleted]
- ColinWright 15y agoOK, as requested: You've missed something. I've just run a few naive tests and all three versions on the linked page give the same result on every test, and yours gives different results on some of the tests. In short, your code doesn't work. So you've missed something.
- deleted 15y ago[deleted]
- ColinWright 15y agoI see you asked, but then deleted, which I can understand. But to answer your question, "obvious" and "obvious" should return 7, but your code returns 0.