編寫一個函數來查找字符串數組中的最長公共前綴。
如果不存在公共前綴,返回空字符串 ""
。
示例 1:
輸入: ["flower","flow","flight"]輸出: "fl"
示例 2:
輸入: ["dog","racecar","car"]輸出: ""解釋: 輸入不存在公共前綴。
說明:
所有輸入只包含小寫字母 a-z
。
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: res = '' if strs: l = list(map(len, strs)) l.sort() list1 = [] for i in range(l[0]): for s in strs: list1.append(s[i]) if len(set(list1)) == 1: res += strs[0][i] list1.clear() continue else: break return res
執行用時 : 76 ms, 在Longest Common Prefix的Python3提交中擊敗了26.44% 的用戶
內存消耗 : 13.1 MB, 在Longest Common Prefix的Python3提交中擊敗了91.31% 的用戶