14. Longest Common Prefix

703次阅读
没有评论

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:

<strong>Input: </strong>["flower","flow","flight"]
<strong>Output:</strong> "fl"

Example 2:

<strong>Input: </strong>["dog","racecar","car"]
<strong>Output:</strong> ""
<strong>Explanation:</strong> 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
admin
版权声明:本站原创文章,由admin2019-02-11发表,共计398字。
转载提示:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)