leetcode 14:最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ''
。
方法一:依次比较
将第一个字符串赋给前缀 prefix
,然后依次比较每个字符串,比较过程中更新前缀。
def longestCommonPrefix(strs):
if not strs:
return ''
prefix = strs[0]
for s in strs[1:]:
while not s.startswith(prefix):
prefix = prefix[:len(prefix)-1]
if not prefix:
return ''
return prefix
startswith()
方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True
,否则返回 False
。
方法二、Python 的解包、打包操作
def longestCommonPrefix(strs):
prefix = ''
for s in zip(*strs):
if len(set(s)) == 1:
prefix += s[0]
else:
break
return prefix
注意利用了 zip()
的一个特性,只返回包含元素个数最短的对象。
方法三、仅比较两个字符串
这里比较的是最小字典序字符串和最大字典序字符串。
若有公共前缀,则在这两个之间一定包含着公共前缀。比作字典中的单词理解就好了。
代码如下:
# min 和 max 对字符串排序是按字典序排序
def longestCommonPrefix(strs):
if not strs:
return ''
s1, s2 = min(strs), max(strs)
for i, c in enumerate(s1):
if c != s2[i]:
return s1[:i]
return s1
方法四、构造字典树
若对字典树不太熟悉的,可以先看 用 Python 实现一个字典树 这篇文章。
def longestCommonPrefix(strs):
if not strs:
return ''
# 构建字典树
root = {}
for word in strs:
if not word: # 处理空字符串
return ''
node = root
for char in word:
node = node.setdefault(char, {})
node['#'] = '#' # 结束标志
res, node = '', root
while node != {'#': '#'}: # 注意判断结束条件
if len(node) == 1:
char, = node # 字典中只有一个 key 时,使用解包操作
res += char
node = node[char]
else:
break
return res