LeetCode(14)-- 最長公共字首
阿新 • • 發佈:2018-12-10
編寫一個函式來查詢字串陣列中的最長公共字首。
如果不存在公共字首,返回空字串 ""
。
輸入: ["flower","flow","flight"]
輸出: "fl"
輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共字首。
class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return "" if len(strs) == 1: return strs[0] minl = min([len(x) for x in strs]) end = 0 while end < minl: for i in range(1,len(strs)): if strs[i][end]!= strs[i-1][end]: return strs[0][:end] end += 1 return strs[0][:end]
如果是空串的話,那麼說明字首就是“”
如果都是以“ ”開頭的,那麼就是“ ”
然後最長的字首不會超過最短的字串,那麼可以遍歷最短的字串的長度,依次比較。
第一步:找出長度最短的字串;
第二步:依次與長度最短的字串比較。