您的位置:首页 > 编程语言 > Python开发

Python学习-Leetcode刷题记5:最长公共前缀

2019-02-01 02:00 411 查看

Python学习-Leetcode刷题记5:最长公共前缀

一、问题

编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
说明:所有输入只包含小写字母 a-z 。

二、示例

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

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

三、解题过程

class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ''
else:
L = min([ len(i) for i in strs])
l = len(strs)
count = 0
for j in range(L):
D = [i[j] for i in strs]
if D.count(D[0]) == l:
count+=1
else:
break
return strs[0][:count]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: