[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)。相关文章推荐
- [Lintcode] #78 最长公共前缀
- lintcode-78-最长公共前缀
- lintcode 78.最长公共前缀
- LintCode 78.最长公共前缀
- LintCode-最长公共前缀
- lintcode :longest common prefix 最长公共前缀
- LintCode-最长公共前缀
- lintcode -- 最长公共前缀
- LintCode 最长公共前缀
- 最长公共前缀 -LintCode
- (78)最长公共前缀
- [LintCode] 最长公共前缀
- Lintcode(6)-最长公共前缀
- lintcode python ——最长公共前缀(LCP)
- lintcode 最长公共前缀
- 78 - 最长公共前缀
- python 实现求解字符串集的最长公共前缀方法
- lintcode-最长公共前缀-78
- LintCode(M)最长公共前缀
- [Lintcode]最长公共前缀