LeetCode(No.14)--最长公共前缀
程序员文章站
2024-02-24 23:15:28
...
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入: [“flower”,“flow”,“flight”]
输出: “fl”
示例 2:
输入: [“dog”,“racecar”,“car”]
输出: “”
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。
本人写的比较low
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
dic = {}
for i in strs:
dic[i] = len(i)
if len(strs) == 0:
return ""
else:
shortItem = min(dic.items(), key=lambda x: x[1])[0]
strs.remove(shortItem)
boolean = True
i = 0
common = ""
while i < len(shortItem) and boolean:
count = 0
for j in range(len(strs)):
if shortItem[:i + 1] == strs[j][:i + 1]:
count += 1
else:
count += 0
if count == len(strs):
common = shortItem[:i + 1]
i += 1
else:
boolean = False
return common
方法2:
class Solution:
def longestCommonPrefix(self, strs: 'List[str]') -> 'str':
if len(strs) == 0:
return ''
if len(strs) == 1:
return strs[0]
prefix, chars = '', zip(*strs)
for i, group in enumerate(chars):
ch = group[0]
for j in range(1, len(group)):
if group[j] != ch:
return prefix
prefix += strs[0][i]
return prefix
方法3:
'''
将list中各元素的每个位置的值放入到一个集合里再做一个映射,值->集合元素个数,
再存入list,然后只要取出元素个数为1的即可
'''
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
strs = list(map(set, zip(*strs)))
result = ''
for i in range(len(strs)):
if len(strs[i]) > 1:
break
else:
result += strs[i].pop()
return result