給出字符串數組,查找這個數組中全部字符串的最長公共前綴python
Write a function to find the longest common prefix string amongst an array of strings.git
example 1github
input: ['asdqowi','asdb', 'asdmnc'] output: 'asd'
i從0開始自增,判斷每一個字符串 i 位置的字符是否一致,不一致則 i 以前的串爲最長公共字符串。算法
利用python zip函數的特色:數組
a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9, 10] zip(a, b, c) is => (1, 4, 7) (2, 5, 8) (3, 6, 9) set((1, 1, 1)) = {'1'} set((1, 1, 2)) = {'1', '2'}
zip(*strs)
返回可迭代的zip對象,只要判斷set(item)
長度大於0,則代表此元素非公共字符。函數
下面給出兩種算法的代碼。code
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ prefix = '' i = 0 while True: try: tmp = strs[0][i] for item in strs: if item[i] != tmp: return prefix except: #out of index range,代表遍歷最短字符串完畢 return prefix prefix += tmp i += 1 return prefix def longestCommonPrefix_use_zip(self, strs): """ :type strs: List[str] :rtype: str """ prefix = '' for _, item in enumerate(zip(*strs)): if len(set(item)) > 1: return prefix else: prefix += item[0] return prefix
本題以及其它leetcode題目代碼github地址: github地址對象