The longest common substring (find the length and find the substring)

problem

The longest common substring problem is to find the longest substring of two or more known strings. The difference between this problem and the longest common subsequence problem is that the subsequence does not have to be continuous, but the substring must be.
Assuming there are two strings, find the longest common continuous substring among them, output its length, and find the longest common substring.

Input:
abcde
bcd
Output:
3
bcd

Ideas

Dynamic planning
Fill out the form

Insert picture description here

Code

def maxLengthStr(a,b):
    n = len(a)
    m = len(b)
    res = [[0 for _ in range(m)] for _ in range(n)]
    for j in range(m):
        if a[0] == b[j]:
            res[0][j] = 1
    for i in range(n):
        if b[0] == a[i]:
            res[i][0] = 1
    max_len = 0
    index = 0
    for i in range(1,n):
        for j in range(1,m):
            if a[i-1] == b[j-1] and a[i] == b[j]:
                res[i][j] = res[i-1][j-1]+1
            if res[i][j] > max_len:
                max_len = res[i][j]
                index = j
    print(res)
    return max_len,index


if __name__ == '__main__':
    a = [1,2,3]
    b = [1,2,3,3,2,1]
    max_len,end = maxLengthStr(a,b)
    start = end-max_len+1
    print('最长公共子串的长度为:',max_len)
    print('最长公共子串的起始索引',start)
    print('最长公共子串的末位索引', end)
    print('最长公共子串为',b[start:end+1])

Written examination questions "perfect arrangement" problem

Input use case:
3
1 2 3
3 2 1
6
1 2 3 3 2 1
3 2 1 1 2 3

Code

def maxLengthStr(a,b):
    n = len(a)
    m = len(b)
    res = [[0 for _ in range(m)] for _ in range(n)]
    for j in range(m):
        if a[0] == b[j]:
            res[0][j] = 1
    for i in range(n):
        if b[0] == a[i]:
            res[i][0] = 1
    max_len = 0
    index = 0
    for i in range(1,n):
        for j in range(1,m):
            if a[i-1] == b[j-1] and a[i] == b[j]:
                res[i][j] = res[i-1][j-1]+1
            if res[i][j] > max_len:
                max_len = res[i][j]
                index = j
    print(res)
    return max_len,index


def ver(a_value, b_value, start, end):
    print(a_value[:])
    print(b_value[start:end+1])
    if a_value[:] == b_value[start:end+1]:
        return True
    return False


if __name__ == '__main__':
    a = [1,2,3]
    a_value = [3,2,1]
    b = [1,2,3,3,2,1]
    # b_value = [5,4,3,2,1,1]
    b_value = [3,2,1,1,2,3]
    max_len,end = maxLengthStr(a,b)
    start = end-max_len+1
    print('最长公共子串的长度为:',max_len)
    print('最长公共子串的起始索引',start)
    print('最长公共子串的末位索引', end)
    print('最长公共子串为',b[start:end+1])
    if ver(a_value, b_value, start, end):
        print("完美排列存在,索引为:",start)
    else:
        print('完美排列不存在!')


Guess you like

Origin blog.csdn.net/weixin_44776894/article/details/108509341