def lcs(i, j):if i == m or j == n: return 0if s[i] == t[j]: return 1 + lcs(i+1, j+1)return max(lcs(i, j+1), lcs(i+1, j))def lcs2(i, j):if i >= m or j >= n: returni0 = i; j0 = jwhile i < m and j < n and s[i] == t[j]: i += 1; j += 1k = (i, j); len = i - i0val = d.get(k, 0)if len > val: d[k] = lenlcs2(i, j+1); lcs2(i+1, j)import sys a = sys.argv if len(a) == 2 and a[1] == '1': s = 'XXabXXd'; t = 'YabYd' else: s = '13542687'; t = '148675' print(s, t) m = len(s); n = len(t); d = {}print(lcs(0,0)) lcs2(0,0) print(max(d.items(), key=lambda x: x[1])[1])
〔链接1〕〔链接2〕〔链接3〕之一说:common sub-string时,s[i] != t[j]时,d[i][j]要清零。