lintcode練習-78. 最長公共字首
阿新 • • 發佈:2019-02-14
78. 最長公共字首
給k個字串,求出他們的最長公共字首(LCP)
樣例
在 "ABCD" "ABEF" 和 "ACEF" 中, LCP 為 "A"
在 "ABCDEFG", "ABCEFG", "ABCEFA" 中, LCP 為 "ABC"
解題思路:
class Solution: """ @param strs: A list of strings @return: The longest common prefix """ def longestCommonPrefix(self, strs): # write your code here if len(strs) == 0: return '' prefix = '' index = 1 while index: prefix = strs[0][:index] print(prefix) COUNT = 0 for str in strs: if str[:index] != prefix: return str[:index-1] if str == prefix: COUNT += 1 if COUNT == len(strs): return prefix index += 1