python3自写小工具

python3 从给定的两个字符串中找出长度最大的公共子串

2020-11-30  本文已影响0人  AmanWang

介绍

该函数可以在给定的字符串str1和str2里找出并返回长度最大的公共子串。详细信息在源码里有说明。源码如下:

def getMaxLenSameSubStr(str1, str2, isLower=False):
    # 说明
    # 该函数是在给定的两个字符串str1和str2中找出长度最长的相同的子串
    # str1和str2分别为给定的两个字符串
    # isLower标记是否区分大小写,False不区分,True区分,默认为False
    # 返回结果为字典格式:{maxLen: [maxSub1, maxSub2, maxSub3, ...]}
    # 没有公共子串的结果为:{0: []}

    # 如果传参不是字符串类型,强制转换,并将短字符串赋值给str1
    str1 = str(str1)
    str2 = str(str2)
    if not str1 or not str2:
        return {0:[]}
    if len(str1) > len(str2):
        str1, str2 = str2, str1

    # 是否区分大小写
    if isLower:
        str1, str2 = str1.lower(), str2.lower()

    # 如果短字符串是长字符串的子串,直接返回短字符串
    sameSubStrDict = {}
    if str1 in str2:
        sameSubStrDict[len(str1)] = [str1]
        return sameSubStrDict
    shortStrLen = len(str1)

    # 处理短字符串并判断短字符串的子串是否在长字符串中存在
    sameSubStrDict[0] = []
    for i in range(0, shortStrLen+1):
        for j in range(0, i-1): # 去掉单字符的情况
            subStr = str1[j:i]
            if subStr in str2:
                # 如果已存在,添加到对应的字典value的列表中
                if len(subStr) in sameSubStrDict.keys():
                    sameSubStrDict[len(subStr)].append(subStr)
                else:
                    sameSubStrDict[len(subStr)] = [subStr]

    # 处理返回结果
    res = {}
    maxLen = max(list(sameSubStrDict.keys()))
    res[maxLen] = sameSubStrDict[maxLen]
    return res

调用及结果

# 调用
if __name__ == '__main__':
    a = 'test'
    b = 'test'
    c = 'test'
    d = 'aatestbbtesthhh'
    e = 'gggTest001'
    f = 'test'
    g = 'gggTest001'
    h = 'test'
    i = ''
    j = 'test'
    k = 'abc'
    l = 'test'
    print('结果1:%s' %(getMaxLenSameSubStr(a, b), ))
    print('结果2:%s' %(getMaxLenSameSubStr(c, d), ))
    print('结果3:%s' %(getMaxLenSameSubStr(e, f), ))
    print('结果4:%s' %(getMaxLenSameSubStr(g, h, isLower=True), ))
    print('结果5:%s' %(getMaxLenSameSubStr(i, j), ))
    print('结果6:%s' %(getMaxLenSameSubStr(k, l), ))

结果
结果1:{4: ['test']}
结果2:{4: ['test']}
结果3:{3: ['est']}
结果4:{4: ['test']}
结果5:{0: []}
结果6:{0: []}
上一篇下一篇

猜你喜欢

热点阅读