编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
1 class Solution: 2 def longestCommonPrefix(self, strs): 3 """ 4 :type strs: List[str] 5 :rtype: str 6 """ 7 if len(strs) == 0: 8 return "" 9 if len(strs) == 1: 10 return strs[0] 11 else: 12 return self.getCommonPrefix(strs,0,len(strs)-1) 13 14 def getCommonPrefix(self,strs,left,right): 15 if left == right: 16 return strs[left] 17 elif right - left == 1: 18 return self.Prefix(strs[left], strs[right]) 19 else: 20 mid = (left + right) // 2 21 astr = self.getCommonPrefix(strs, left, mid) 22 bstr = self.getCommonPrefix(strs, mid + 1, right) 23 return self.Prefix(astr, bstr) 24 25 def Prefix(self,str1,str2): 26 prefix = "" 27 if len(str1)>len(str2): 28 tmp=str1 29 str1=str2 30 str2=tmp 31 for i,a in enumerate(str1): 32 if a==str2[i]: 33 prefix = prefix+a 34 else: 35 break 36 37 return prefix 38
原文地址:https://www.cnblogs.com/chengchengaqin/p/9508961.html
时间: 2024-10-09 06:57:19