题目要求:
求解思路:
1.横向扫描:
定义一个实现比较两个字符串最长公共前缀的函数:LCP
LCP(S1.....Sn)=LCP(LCP(LCP(S1,S2),S3),......Sn)
2.纵向扫描:
从前往后遍历所有字符串的每一列
3.基于python特性的求法
3.1使用列表sort函数:
思路:strs.sort()函数,在列表内容是字符串的时候,会按位依次比较阿斯克码值,也就是说abb一定会在abc的前面,那么我们进行排序后,只需要比较strs[0]与strs[-1]的最长前缀就能实现了:
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
strs.sort()
length,index = min(len(strs[0]),len(strs[-1])),0
while index < length and strs[0][index] == strs[-1][index]:
index +=1
return strs[0][:index]
3.2 利用zip与set
思路:使用zip组合str对象的时候,譬如a ='aabbcc',b='ccdd',使用zip(a,b)时,会获得一个
{[a,c],[a,c],[b,d],[b,d]}的元组对象,那么我们使用set(zip(a,b)[index])是不是就能按位判断了
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
index = 0
for comba in zip(*strs):
if len(set(comba)) == 1:
index +=1
else:
break
return strs[0][:index]