题目描述
找出字符串列表中各个字符串的最长公共前缀字符
分析
使用reduce()函数,依次对列表中的字符串调用lcp()内方法,对字符串迭代使用lcp方法来判断。
reduce(function,iterable):依次取出iterable的元素,作为function的参数,并且上一次调用function的返回值,也作为iterable的一个元素
lcp(s1,s2): 循环遍历较短字符串的每个字符,当遇到不同字符时停止,并返回该不同字符之前的所有字符作为返回.
完整代码
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
def lcp(s1,s2): #内方法
if len(s1)>len(s2): #令s1保存较短的字符串
s1,s2=s2,s1 #两个字符串互换位置
for i in range(len(s1)): #遍历较短字符串
if s1[i]!=s2[i]: #若第i个字符不一致
return s1[:i] #返回i之前的字符
return s1 #若s1是s2的前缀,直接返回s1
return reduce(lcp,strs) if strs else ''