码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode_78最长公共前缀

时间:2017-12-09 20:45:46      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:abc   ring   str   lint   lin   self   com   style   pre   

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

 

样例

在 "ABCD" "ABEF" 和 "ACEF" 中,  LCP 为 "A"

在 "ABCDEFG", "ABCEFG", "ABCEFA" 中, LCP 为 "ABC"

class Solution:
    """
    @param: strs: A list of strings
    @return: The longest common prefix
    """
    def longestCommonPrefix(self, strs):
        if not strs: #strs为空要求返回""
            return ""
        if len(strs)<2: 
            return strs[0]
        
        for j in range(len(strs[0])):
            for i in range(1,len(strs)):
                if not strs[i]: #列表中存在空元素则返回"",无公共前缀
                    return ""
                elif strs[0][j] != strs[i][j]:
                    return strs[0][:j]
        return strs[0]

以第一个元素作为参照与后面每一个元素比较

 

九章参考解:

class Solution:
    # @param strs: A list of strings
    # @return: The longest common prefix
    def longestCommonPrefix(self, strs):
        if len(strs) <= 1:
            return strs[0] if len(strs) == 1 else ""
        end, minl = 0, min([len(s) for s in strs])
        while end < minl:
            for i in range(1, len(strs)):
                if strs[i][end] != strs[i-1][end]:
                    return strs[0][:end]
            end = end + 1
        return strs[0][:end]

 

lintcode_78最长公共前缀

标签:abc   ring   str   lint   lin   self   com   style   pre   

原文地址:http://www.cnblogs.com/zhangli-ncu/p/8012361.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!