# 外层循环为列表中第一个元素的长度,内层循环为列表元素的个数
# 即列表的长度
def LongestCommonPrefix(lst):
if not lst:
return ""
else:
index = 0
for i in range(len(lst[0])):
for j in range(1, len(lst)):
if i >= len(lst[j]) or lst[0][i] != lst[j][i]:
return lst[0][:index]
index += 1
return lst[0][:index]
In [2]: lst = ["abcdefg", "abcdefghijk", "abcdfghijk", "abcef"]
In [3]: print(LongestCommonPrefix(lst))
abc