Determine prefix from a set of (similar) strings

前端 未结 9 2139
我在风中等你
我在风中等你 2020-11-27 14:25

I have a set of strings, e.g.

my_prefix_what_ever
my_prefix_what_so_ever
my_prefix_doesnt_matter

I simply want to find the longest common p

9条回答
  •  误落风尘
    2020-11-27 14:57

    Here's my solution:

    a = ["my_prefix_what_ever", "my_prefix_what_so_ever", "my_prefix_doesnt_matter"]
    
    prefix_len = len(a[0])
    for x in a[1 : ]:
        prefix_len = min(prefix_len, len(x))
        while not x.startswith(a[0][ : prefix_len]):
            prefix_len -= 1
    
    prefix = a[0][ : prefix_len]
    

提交回复
热议问题