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