在字符串列表中找到最长的公共前缀字符串

时间:2020-11-01 02:23:50

标签: python

我正在使用python,我必须编写一个函数以在字符串列表中找到最长的公共前缀字符串。
例如,输入参数为["flower", "flow", "flight"], 输出为"fl"。如果输入字符串中没有通用前缀, 输出为空字符串。

2 个答案:

答案 0 :(得分:2)

您可以将字符串zip(*list_o_strings)压缩在一起,这将给您类似('f', 'f', 'f')的元组。如果将它们传递给集合,则当所有字母相同时,集合将只有一个值。只需在那个拉链上循环,直到找到长度大于一个的集合。

def common_prefix(l):
    s = ''
    for c, *rest in  map(set, zip(*l)):
        if rest:  # rest will be empty of the set is shorter than 1
            return s
        s += c
    
common_prefix(["flower", "flow", "flight"])
# 'fl'

common_prefix(["flower", "flow", "flog"])
# 'flo'

common_prefix(["glower", "flow", "flight"])
# ''

答案 1 :(得分:0)

def get_prefix_str(str_list):
    # take first string as reference and compare each char with the corresponding char of the rest of strings
    prefix_str = ''
    len_smallest_str = min([len(str_mem) for str_mem in str_list])
    for i in range(len_smallest_str): 
        if len([0 for ind in range(1, len(str_list)) if str_list[0][i] != str_list[ind][i]]) > 0:
            break 
        prefix_str += str_list[0][i]
    return prefix_str

for str_list in [["flower", "flow", "flight"], ["lower", "low", "light"], ["ower", "ow", "ight"]]:
    print(str_list)
    prefix_str = get_prefix_str(str_list)
    print(f'Prefix is {prefix_str}')

输出:

['flower', 'flow', 'flight']
Prefix is fl
['lower', 'low', 'light']
Prefix is l
['ower', 'ow', 'ight']
Prefix is