finding common prefix of array of strings

后端 未结 17 1700
一向
一向 2020-11-29 06:15

I have an array like this:

$sports = array(
\'Softball - Counties\',
\'Softball - Eastern\',
\'Softball - North Harbour\',
\'Softball - South\',
\'Softball -         


        
17条回答
  •  无人及你
    2020-11-29 06:36

    I assume that by "common part" you mean "longest common prefix". That is a much simpler to compute than any common substring.

    This cannot be done without reading (n+1) * m characters in the worst case and n * m + 1 in the best case, where n is the length of the longest common prefix and m is the number of strings.

    Comparing one letter at a time achieves that efficiency (Big Theta (n * m)).

    Your proposed algorithm runs in Big Theta(n^2 * m), which is much, much slower for large inputs.

    The third proposed algorithm of finding the longest prefix of the first two strings, then comparing that with the third, fourth, etc. also has a running time in Big Theta(n * m), but with a higher constant factor. It will probably only be slightly slower in practice.

    Overall, I would recommend just rolling your own function, since the first algorithm is too slow and the two others will be about equally complicated to write anyway.

    Check out WikiPedia for a description of Big Theta notation.

提交回复
热议问题