function getLongestMatchingSubstring($str1, $str2)
{
$len_1 = strlen($str1);
$longest = '';
for($i = 0; $i < $len_1; $i++){
for($j = $len_1 - $i; $j > 0; $j--){
$sub = substr($str1, $i, $j);
if (strpos($str2, $sub) !== false && strlen($sub) > strlen($longest)){
$longest = $sub;
break;
}
}
}
return $longest;
}
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (2)
Great solution to the problem. I think there might be several improvements though.
Love the challenge, I'll create an alternative and benchmark this later...
So, I played around a bit, sadly didn't have time for deeper look and a lot of tries. Here is my quick solution to this:
This seems to outperform the posted solution in most cases (by a huge factor up to 500 or more). For the extreme examples of having one very long string and one very short, both solutions seem to be pretty close, depending on the string order. While the order can easily be fixed, this still is way quicker in most "normal" circumstances.
Let me know if you find even better solutions. :-)