題目:
Write a function to find the longest common prefix string amongst an array of strings.
找到一個數(shù)組中最長的公共前綴闸迷。
思路:
1.先找到其中最短的字符串
2.然后逐一與這個最短的進行比較
將字符串數(shù)組根據(jù)長度排序的方法:
str.sort(key=lambda x:len(x))
或者直接:str.sort(key=len)
enumerate 函數(shù)用于遍歷序列(list,tuple)中的元素以及它們的下標:
>>> for i,j in enumerate(('a','b','c')):
print i,j
0 a
1 b
2 c
最后的代碼:
def longestCommonPrefix(self, strs):
? ?#typr strs:list[str]
? ?#rtypr:str
? ?if not strs:
? ?return ' '
? ?shortest =min(strs,key=len)
? ?fori,ch in enumerate(shortest):
? ?for other in strs:
? ? ? ?if other[i] != ch:
? ? ? ? ? ? ?return shortest[:i]
? ?return shortest