#横向扫描
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
def lcp(str1, str2): #定义查找函数
length = min(len(str1), len(str2))
index = 0 #从第一个字母开始检索
while index < length and str1[index] == str2[index]:
index += 1
return str1[:index]
if not strs:
return ''
prefix = strs[0] #从第一个字符串开始
for i in range(1, len(strs)):
prefix = lcp(prefix, strs[i])
if not strs:
break
return prefix
#纵向扫描
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
length = len(strs[0]) #第一个字符串长度
count = len(strs) #列表长度
for i in range(length):
prefix = strs[0][i]
if any(i == len(strs[j]) or strs[j][i] != prefix for j in range(1, count)):
return strs[0][:i]
return strs[0]