题目
分析
可以使用归并的思想来做,每两个串left 和right合并出最长公共前缀res,然后res之间再合并。
python代码
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs: return ""
return self.mergeSort(strs,0,len(strs)-1)
def mergeSort(self,strs,begin,end):
if begin==end:
return strs[begin]
mid = (begin+end)>>1
left = self.mergeSort(strs,begin,mid)
right = self.mergeSort(strs,mid+1,end)
return self.merge(left,right)
def merge(self,left,right):
if len(right)<len(left):
left,right = right,left
res = ""
for i in range(len(left)):
if left[i]==right[i]:
res+=left[i]
else:
break
return res