欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[LintCode]最长公共前缀python

程序员文章站 2022-07-05 13:07:21
...

1.用到了map函数,不会的可以先看看

1.利用map函数计算出每一个字符串的长度
2.根据长度进而获得最短字符串的下标
3.循环对比获得一个列表
4.判断上面获取的列表当没有False时,返回结果
def longestCommonPrefix(strs):
    if len(strs) < 1:
        return ""
    a = list(map(lambda x:len(x), strs))
    b = min(a)
    c = a.index(b)
    for i in range(b):
        d = list(map(lambda x:strs[c][:b-i:] in x[:b-i], strs))
        if False not in d:
            return strs[c][:b-i:]

    return ""
if __name__ == '__main__':
    strs = ["ca","a"]
    print(longestCommonPrefix(strs))

2.利用zip函数

利用zip函数,其中*去维数
def longestCommonPrefix(strs):

    prefix = ''
    for item in list(zip(*strs)):
        print(item)
        if len(set(item)) > 1:
            return prefix
        else:
            prefix += item[0]
    return prefix

if __name__ == '__main__':
    strs = ["flower","flow","flight"]
    print(longestCommonPrefix(strs))
def longestCommonPrefix(strs):

    if len(strs) <= 0: return ""
    common_str = ""
    for i in range(len(strs[0])):
        common_str += strs[0][i]
        for single_str in strs[1:]:
            if len(single_str) <= i: return common_str[:-1]
            if single_str[i] != common_str[-1]: return common_str[:-1]

    return common_str

if __name__ == '__main__':
    strs = ["flower","flow","flight"]
    print(longestCommonPrefix(strs))
相关标签: LintCode