问题描述
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
- 示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
- 示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
- 说明:
所有输入只包含小写字母 a-z。
问题解答
方法一 将字符串列表排序,从最短的两个字符串取得其公共前缀,然后横向扫描得到结果
def longestCommonPrefix(self, strs: List[str]) -> str:
if strs != []:
len_lst = []
#构建字符串及其字符串长度的列表,稍后看到第二种方法发现这是画蛇添足
for item in strs:
len_lst.append([len(item), item])
#对得到列表进行排序,从最短的两个字符串开始取得公共前缀
len_lst.sort()
common_part = len_lst[0][1]
#依次遍历字符串列表,得出最终公共前缀
for i in range(1, len(len_lst)):
while common_part != len_lst[i][1][:len(common_part)]:
common_part = common_part[:-1]
else:
common_part = ""
return common_part
执行用时 : 52ms
思考
方法一是基于如下思考:公共前缀是所有字符串共有的, 那么从最短的两个字符串开始找公共前缀相对来说会简便一些。如下例子,是一个排好序的字符串列表。
[‘aacbc’, ‘aacdde’, ‘aacdfe’, ‘aacpo’, ‘ab’]
在python中字符串排序,即字符串比较是按照单个字符进行比较的。意味着在排序的过程中,其实已经在实现寻找公共前缀的功能。基于此,有如下方法二。
方法二 字符串排序,比较"最大最小"即可
def longestCommonPrefix(self, strs: List[str]) -> str:
if strs != []:
commonprefix = min(strs)
str_max = max(strs)
#比较最大最小字符串,得到其公共前缀即为整个字符串列表的公共前缀
while commonprefix != str_max[:len(commonprefix)]:
commonprefix = commonprefix[:-1]
#求公共前缀另一种实现
#commonprefix = ""
#str_min = min(strs)
#str_max = max(strs)
#for i in range(len(min(strs))):
#if str_min[i] == str_max[i]:
#commonprefix = commonprefix + str_min[i]
#else:
#break
else:
commonprefix = ""
return commonprefix
执行用时 : 50ms