14.最长公共前缀
方法一:横向扫描
依次遍历字符串数组中的每个字符串,对于每个遍历到的字符串,更新最长公共前缀,当遍历完所有的字符串以后,即可得到字符串数组中的最长公共前缀。
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if str is None:
return ""
prefix,count = strs[0],len(strs)
for i in range(1,count):
prefix = self.lcp(prefix,strs[i])
if prefix is None:
break
return prefix
def lcp(self,str1,str2):
length,index = min(len(str1),len(str2)),0
while index < length and str1[index] == str2[index]:
index += 1
return str1[:index]
strs = ["flower","flow","flight"]
l = Solution()
l.longestCommonPrefix(strs)
方法二:纵向扫描
方法一是横向扫描,依次遍历每个字符串,更新最长公共前缀。另一种方法是纵向扫描。纵向扫描时,从前往后遍历所有字符串的每一列,比较相同列上的字符是否相同,如果相同则继续对下一列进行比较,如果不相同则当前列不再属于公共前缀,当前列之前的部分为最长公共前缀。
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
length, count = len(strs[0]), len(strs)
for i in range(length):
c = strs[0][i]
if any(i == len(strs[j]) or strs[j][i] != c for j in range(1, count)):
return strs[0][:i]
return strs[0]