编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”
输入:strs = [“flower”,“flow”,“flight”]
输出:“fl”
from typing import List
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
headStr=strs[0]
for i in range(1,len(strs)):
headStr =self.maxPrex(headStr,strs[i])
if not headStr:
break
return headStr
def maxPrex(self,str1,str2):
index,lenth=0,min(len(str1),len(str2))
while index<lenth and str1[index]==str2[index]:
index +=1
return str1[:index]
s = ["flower","flow","flight"]
a= Solution().longestCommonPrefix(s)
print(a)