您的位置:首页 > 其它

Datawhale-LeetCode集训打卡-最长公共前缀

2019-01-31 14:46 344 查看

Datawhale-LeetCode集训打卡-最长公共前缀

Datawhale-LeetCode集训打卡-第五天-最长公共前缀(Longest Common Prefix)

Solution - Longest Common Prefix using Sorting

class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
size = len(strs)

# if size is 0, return empty string
if (size == 0):
return ""

if (size == 1):
return strs[0]

# sort the array of strings
strs.sort()

# find the minimum length from first and last string
end = min(len(strs[0]), len(strs[size - 1]))

# find the common prefix between the first and last string
i = 0
while (i < end and strs[0][i] == strs[size - 1][i]):
i += 1

pre = strs[0][0: i]
return pre
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: