1. 程式人生 > >[LintCode]最長公共字首python

[LintCode]最長公共字首python

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))