您的位置:首页 > 其它

Leetcode14. 最长公共前缀

2019-01-26 15:48 375 查看

Leetcode14. 最长公共前缀

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

如果不存在公共前缀,返回空字符串 “”。
实例:
示例 1:

输入: [“flower”,“flow”,“flight”]
输出: “fl”
示例 2:

输入: [“dog”,“racecar”,“car”]
输出: “”
解释: 输入不存在公共前缀。
解法1:(python)

class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
result = ""
if len(strs) > 0:
x = strs[0]
for i, n in enumerate(x):
for j in range(1,len(strs)):
if i <= (len(strs[j])-1) and n == strs[j][i]:
continue
else:
return result
result += n
return result
else:
return result

解法1优化版:

class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
#判断是否为空
if not strs:
return ""

# 找到最短的字符串
shortest = min(strs, key=len)

# 转换为枚举对象
for i_th, letter in enumerate(shortest):

for other in strs:

if other[i_th] != letter:

return shortest[:i_th]

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