# 阶梯训练1-字符串处理

78. 最长公共前缀

defgetCommon(self,strA,strB):

lenA = len(strA)

lenB = len(strB)

result =''

length = min(lenA,lenB)

foriinrange(length):

ifstrA[i]==strB[i]:

result = result + strA[i]

else:

returnresult

returnresult

longestCommonPrefix函数中，如果字符串为空，返回‘’

deflongestCommonPrefix(self,strs):

iflen(strs)==:

return''

result = strs[]

length = len(strs)

foriinrange(1,length):

print(result)

result =self.getCommon(result,strs[i])

returnresult

79. 最长公共子串

deflongestCommonSubstring(self,A,B):

lengthA = len(A)

lengthB = len(B)

iflengthA == lengthBandlengthA ==:

return

iflengthA ==orlengthB ==:

return

length = lengthA

whilelength >=1:

A字符串从位置0开始比较，起始位置+比较字符串长度不得超过A字符串最大长度，

startA =

whilestartA + length

if notB.find(A[startA:length + startA]) == -1:

# print(length,A[startA:length+startA],B.find(A[startA:length+startA]))

returnlength

startA +=1

length -=1

• 发表于:
• 原文链接http://kuaibao.qq.com/s/20180311G0BXDJ00?refer=cp_1026
• 腾讯「云+社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 yunjia_community@tencent.com 删除。

2021-12-08

2021-12-08

2018-07-03

2018-04-26

2021-12-08

2021-12-08

2021-12-08

2021-12-08