14. Longest Common Prefix

2,334次阅读
没有评论

共计 398 个字符,预计需要花费 1 分钟才能阅读完成。

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

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

解法:
class Solution:
    def longestCommonPrefix(self, strs: 'List[str]') -> 'str':
        if len(strs)<1:
            return ''
        min_length=min(map(lambda x:len(x),strs))
        if min_length<1:
            return ''
        result=''
        for x in range(min_length):
            tmp=set([ data[x] for data in strs])
            if len(tmp)==1:
                result+=strs[0][x]
            else:
                return result
正文完
请博主喝杯咖啡吧!
post-qrcode
 
admin
版权声明:本站原创文章,由 admin 2019-02-11发表,共计398字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码