Leetcode 14.最长公共前缀(Python3)

14.最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀。

如果不存在公共前缀,返回空字符串 ""

示例 1:

输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

说明:

所有输入只包含小写字母 a-z 。

 

自己的代码:

#longest-common-prefix
class Solution(object):

    def longestCommonPrefix(self,strs):
        if len(strs) == 0 or strs[0] == '':
            return ''
        if len(strs) == 1:
            return strs[0]
        m = min([len(x) for x in strs])
        for j in range(m):
            for i in range(1,len(strs)):
                if strs[0][j] != strs[i][j]:
                    return strs[0][:j]
        return strs[0][:m]

if __name__ == '__main__':
    print(Solution().longestCommonPrefix(["abca","aba","aaab"]))

执行用时:52 ms

 

链接:

https://leetcode-cn.com/problems/longest-common-prefix/description/

你可能感兴趣的:(leetcode,python3)