14 | Longest Common Prefix | 31.60% | list中各string的最长重复string前缀 |
string是“”,char是‘’ |
reduce():跟r里面的apply类似 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 6 16:11:51 2018
@author: vicky
"""
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
#string是“”,char是‘’
if len(strs)==0:
return ""
else:
p=strs[0]
for i in range(len(strs)-1):
t=str()
for j in range(min(len(p),len(strs[i+1]))):
#注意strs[]表示string,strs[][]表示第几个字母
if p[j]==strs[i+1][j]:
t=t+strs[i+1][j]
else:
break
p=t
return p
strs=["aa","aa"]
strs=["aca","cba"]
strs=["abc","abdf","acdg","abcfgh"]
Solution().longestCommonPrefix(strs)
from functools import reduce
#reduce()用法:跟r里面的apply类似
# reduce(lambda x,y:x*y,range(1,3),5) //lambda 函数,5是初始值, 1*2*5
# reduce(lambda x,y:x*y,range(1,6)) //阶乘,1*2*3*4*5
# reduce(lambda x,y:x*y,range(1,6),3) //初始值3,结果再*3
# http://www.cnblogs.com/zhoujinyi/archive/2013/06/07/3121976.html
class Solution:
def longestCommonPrefix(self, strs):
def lcp(s, t):
if len(s)>len(t):
s, t = t, s
for i in range(len(s)):
if s[i]!=t[i]:
return s[:i]
return s
return reduce(lcp,strs) if strs else ""