python 最先出现的最长公共字串

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 最先出现的最长公共字串相关的知识,希望对你有一定的参考价值。

"""
input: wepicabc, epiabcni
output: epi

solution: suffix array
"""


def maxIntersectSubStr(A, B):
    sufStrA = [(A[i:], 0) for i in range(len(A))]
    sufStrB = [(B[i:], 1) for i in range(len(B))]
    newSufStr = sufStrA + sufStrB
    newSufStr.sort(key=lambda x: x[0])
    maxSubStr, maxLen, pos = "", 0, -1
    for i in range(len(newSufStr)-1):
        # should not be the same array
        if newSufStr[i][1] != newSufStr[i+1][1]:
            length = 0
            minLen = min(len(newSufStr[i][0]), len(newSufStr[i+1][0]))
            while length < minLen and newSufStr[i][0][length] == newSufStr[i+1][0][length]:
                length += 1
            if length > maxLen or length == maxLen and minLen > pos:
                maxSubStr, maxLen, pos = newSufStr[i][0][:length], length, minLen
    return maxSubStr


def main():
    A, B = "wepicabc", "epiabcni"
    maxSubStr = maxIntersectSubStr(A, B)
    print(maxSubStr)


if __name__ == "__main__":
    main()

以上是关于python 最先出现的最长公共字串的主要内容,如果未能解决你的问题,请参考以下文章

【python】求两个字符串的公共字串?

python 最长重复出现字串

最长递归子序列最长公共字串最长公共子序列编辑距离

lintcode_79最长公共字串

LCS 求最长公共子序列

dp-最长公共子序列(LCS)