[LintCode 78] 最长公共前缀(Python)

来源:互联网 发布:海森矩阵的逆矩阵 编辑:程序博客网 时间:2024/06/11 09:36

思路描述

给k个字符串,求出他们的最长公共前缀(LCP)

样例
在 “ABCD” “ABEF” 和 “ACEF” 中, LCP 为 “A”

思路

  • 法一:用python的zip函数解决
  • 法二:两两比较

代码

class Solution:    """    法一:使用zip函数    @param: strs: A list of strings    @return: The longest common prefix    """    def longestCommonPrefix(self, strs):        # write your code here        if strs is None or len(strs) == 0:            return ''        for i in range(len(strs)):            strs[i] = list(strs[i])        tmp = zip(*strs)        res = ''        for i in tmp:            if len(set(i)) == 1:                res += i[0]        return res    """    两两比较    @param: strs: A list of strings    @return: The longest common prefix    """    def longestCommonPrefix1(self, strs):        # write your code here        if strs is None or len(strs) == 0:            return ''        res = strs[0]        for i in range(1, len(strs)):            tmp = res            res = ''            for j in range(min(len(strs[i]),len(tmp))):                if tmp[j] == strs[i][j]:                    res += tmp[j]                else:                    break        return res

复杂度分析

时间复杂度O(kn),空间复杂度O(1)

原创粉丝点击