编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
输入: ["flower","flow","flight"] 输出: "fl"
示例 2:
输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z
。
第一种思路:
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
return os.path.commonprefix(strs)
第二种思路:
先找到最短的单词的长度min_l,初始化公共前缀common为首元素的[: min_l]
然后从头开始对每个单词进行比较,比较过程中不断更新当前最长公共前缀的长度min_l, 和当前最长公共前缀common。
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
min_l = len(strs[0])
for word in strs:
min_l = min(min_l, len(word))
common = strs[0][:min_l]
# print common
for index, item in enumerate(strs):
i = 0
while(i < min_l and item[i] == common[i]):
i += 1
min_l = min(min_l, i)
common = common[:min_l]
return common
第三种思路:
python里的字符串可以通过ascii的形式进行比较,所以只要找出最大的字符串和最小的字符串进行比较,就可以找到最长公共前缀。
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
mins = min(strs)
maxs = max(strs)
for index, item in enumerate(mins):
if maxs[index] != mins[index]:
return mins[:index]
return mins
第四种思路:
跟第三种思路一样都利用了字符串的比较,但是额外用了zip函数来组合最大字符串和最小字符串。
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
strs.sort()
res = ""
for x, y in zip(strs[0], strs[-1]):
if x == y:
res += x
else:
break
return res