Bootstrap

寻找最大子串长度

寻找最大子串长度

字符不连续

思路:

1.s1长度为m,s2长度为n,建立一个m*n的表board,当s1上字符s1[i]和s2上字符s2[j]相等,记board[i][j]为True否则为False
2.根据1建好的表开始递归,起始位置为board[0][0]
2.1查找每一行最左边的True,因为同一行左边的True的子串必然不小于右边的Ture
2.2此时坐标为i,j那么就从i+2, j+2进行下一层递归,新的起始位置为board[i+2][j+2]

代码

s1 = '0102030405'
s2 = '111213141516'

def f(s1, s2):
    def find(start_i, start_j):
        ret = 0
        for i in range(start_i, m):
            for j in range(start_j, n):
                if board[i][j]:
                    ret = max(ret, 1 + find(i + 2, j + 2))
                    break
        return ret

    m = len(s1)
    n = len(s2)
    board = [[False for j in range(n)] for i in range(m)]
    for i in range(m):
        for j in range(n):
            if s1[i] == s2[j]:
                board[i][j] = True
    start_i = 0
    start_j = 0
    return find(start_i, start_j)

if __name__ == '__main__':
    print(f(s1, s2))

运行结果:

5

备注:

如果子串可连续,把第9行的2改成1即可。

;