classSolution(object): deflongestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ iflen(strs)<1: return"" iflen(strs) ==1: return strs[0] minElement = strs[0] for i inrange(len(strs)): iflen(strs[i])<len(minElement): minElement = strs[i] left = 0 right =len(minElement) mid = (left+right)//2 while left<right: flag = True for j inrange(len(strs)): if minElement[:mid+1] != strs[j][:mid+1]: right = mid flag = False break if flag : left = mid+1 mid = (left+right)//2 return minElement[:mid]
ZIP()大法
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: deflongestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ res = "" for tmp inzip(*strs): tmp_set = set(tmp) iflen(tmp_set) == 1: res += tmp[0] else: break return res