美文网首页
014- Longest Common Prefix

014- Longest Common Prefix

作者: 英武 | 来源:发表于2019-04-12 11:11 被阅读0次

    Longest Common Prefix

    Write a function to find the longest common prefix string amongst an array of strings.

    使用最挫的算法,挨个遍历,居然也能过:

    class Solution(object):
        def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
            if not strs:
                return ''
            res = ''
            for i in range(len(strs[0])):
                for j in range(1, len(strs)):
                    if i >= len(strs[j]) or strs[j][i] != strs[0][i]:
                        return res
                res += strs[0][i]
            return res
    

    参考网页,还有两个算法,一个是先排序:

    class Solution(object):
        def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
            if not strs:
                return ''
            strs.sort()
            res = ''
            for i in range(len(strs[0])):
                if i >= len(strs[-1]) or strs[-1][i] != strs[0][i]:
                    return res
                res += strs[0][i]
            return res
    

    还有一个是使用zip方法,非常简练, 能超过100%的人:

    class Solution(object):
        def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
            if not strs:
                return ''
            for i, chars in enumerate(zip(*strs)):
                if len(set(chars)) > 1:
                    return strs[0][:i]
            return min(strs)
    

    最终结果还是比较有趣的,先排序的时间居然最少。

    再来一个时间最少的:

    class Solution(object):
        def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
            if not strs:
                return ""
            res = 0
            for chars in zip(*strs):
                if len(set(chars)) > 1:
                    return strs[0][:res]
                res += 1
            return min(strs)
    

    注意这里的 zip(*strs)的做法,可以通过这样的方式求转置。

    还有一个先找到最短长度的方法:

    class Solution:
        def longestCommonPrefix(self, strs):
            """
            :type strs: List[str]
            :rtype: str
            """
            if not strs:
                return ''
            shortest = min(strs, key=len)
            for i, v in enumerate(shortest):
                for s in strs:
                    if s[i] != v:
                        return s[:i]
            return shortest
    

    相关文章

      网友评论

          本文标题:014- Longest Common Prefix

          本文链接:https://www.haomeiwen.com/subject/qsgqwqtx.html