编写一个函数来查找字符串数组中的最长公共前缀。数组
若是不存在公共前缀,返回空字符串 ""。函数
示例 1:spa
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:code
输入: ["dog","racecar","car"]
输出: ""blog
解释: 输入不存在公共前缀。
说明:leetcode
全部输入只包含小写字母 a-z 。字符串
方法一:it
1 class Solution: 2 def longestCommonPrefix(self, strs: List[str]) -> str: 3 result = "" 4 i = 0 5 while True: 6 try: 7 #使用set方法,查找第 i 个位置不一样的字母有多少个 8 sets = set(item[i] for item in strs ) 9 #若是个数为 1 则并入到 result 中,并从set中删除保留的哪个数据 10 if len(sets) == 1: 11 result += sets.pop() 12 i += 1 13 else:break 14 except Exception: 15 break 16 return result
方法二:io
1 class Solution: #查找最大公共前缀 2 def longestCommonPrefix(self, strs): 3 if not strs: 4 return "" 5 for i in range(len(strs[0])): 6 for item in strs[1:]: 7 if i >= len(item) or item[i] != strs[0][i]: 8 return strs[0][:i] 9 return ""
来源:力扣(LeetCode)
连接:https://leetcode-cn.com/problems/longest-common-prefixclass