首页 > 其他 > 详细

leetcode-easy-string-14 Longest Common Prefix

时间:2019-06-10 14:06:41      阅读:98      评论:0      收藏:0      [点我收藏+]

mycode   91.59%

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if not strs:
            return ‘‘
        res = ‘‘
        minlen = min([len(s) for s in strs])
        for i in range(minlen):
            alpha = strs[0][i]
            if not all([s[i]==alpha for s in strs[1:]]):
                return res
            res += alpha
        return res

 

参考

思路 : 从后往前逐步缩短搜索的位置

注意:

s = ‘asdc‘
s[:8] 是可以输出s的,不会报错

class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        # initialize common str as the first in list, loop array and shorten it
        if not strs:
            return ""
        prefix = strs[0]
        for s in strs:
            n = len(prefix)
            while n > 0 and prefix[:n] != s[:n]:
                n -= 1
            prefix = s[:n]
        return prefix

 

leetcode-easy-string-14 Longest Common Prefix

原文:https://www.cnblogs.com/rosyYY/p/10997044.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!