您的位置:首页 > 编程语言 > Python开发

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

2017-09-05 10:51 323 查看

思路描述

给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)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: