finding common prefix of array of strings

后端 未结 17 1639
一向
一向 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:50

    How about something like this? It can be further optimised by not having to check the lengths of the strings if we can use the null terminating character (but I am assuming python strings have length cached somewhere?)

    def find_common_prefix_len(strings):
        """
        Given a list of strings, finds the length common prefix in all of them.
        So
        apple
        applet
        application
        would return 3
        """
        prefix          = 0
        curr_index      = -1
        num_strings     = len(strings)
        string_lengths  = [len(s) for s in strings]
        while True:
            curr_index  += 1
            ch_in_si    = None
            for si in xrange(0, num_strings):
                if curr_index >= string_lengths[si]:
                    return prefix
                else:
                    if si == 0:
                        ch_in_si = strings[0][curr_index]
                    elif strings[si][curr_index] != ch_in_si:
                        return prefix
            prefix += 1
    

提交回复
热议问题