说明:最长字串指两字符串中按序但不要求相邻的最长公共部分
比如:“ABSD”与“ASBD”的最长字串为“ASD”
#coding:u8
import numpy as np
def LCS(s1,s2):
C=np.zeros((len(s1)+1,len(s2)+1),np.uint8)
B=np.empty((len(s1)+1,len(s2)+1), np.dtype('U25'))
for i in range(1,len(s1)+1):
for j in range(1,len(s2)+1):
if s1[i-1]==s2[j-1]:
C[i,j]=C[i-1,j-1]+1
B[i,j]="↖"
elif C[i-1,j]>C[i,j-1]:
C[i,j]=C[i-1,j]
B[i,j]="↑"
else:
C[i,j]=C[i,j-1]
B[i,j]="←"
print(C)
print(B)
maxSubStr=""
def getStr(i,j):
nonlocal maxSubStr
if i==0 or j==0:
return
if B[i,j]=="↖":
maxSubStr+=s1[i-1]
getStr(i-1,j-1)
elif B[i,j]=="↑":
getStr(i-1,j)
else:
getStr(i,j-1)
getStr(len(s1),len(s2))
print("最长子字符串为:",maxSubStr)
输出结果
[[0 0 0 0 0 0 0 0 0 0 0 0]
[0 1 1 1 1 1 1 1 1 1 1 1]
[0 1 1 2 2 2 2 2 2 2 2 2]
[0 1 1 2 2 3 3 3 3 3 3 3]
[0 1 2 2 2 3 4 4 4 4 4 4]
[0 1 2 2 2 3 4 4 4 4 4 4]
[0 1 2 3 3 3 4 5 5 5 5 5]
[0 1 2 3 3 3 4 5 5 5 5 5]
[0 1 2 3 3 4 4 5 5 5 5 6]
[0 1 2 3 3 4 5 5 5 5 5 6]
[0 1 2 3 3 4 5 6 6 6 6 6]]
[['' '' '' '' '' '' '' '' '' '' '' '']
['' '↖' '←' '←' '←' '↖' '←' '←' '←' '←' '←' '↖']
['' '↑' '←' '↖' '←' '←' '←' '↖' '←' '←' '←' '←']
['' '↖' '←' '↑' '←' '↖' '←' '←' '←' '←' '←' '↖']
['' '↑' '↖' '←' '←' '↑' '↖' '←' '←' '←' '←' '←']
['' '↑' '↑' '←' '←' '↑' '↑' '←' '←' '←' '←' '←']
['' '↑' '↑' '↖' '←' '←' '↑' '↖' '←' '←' '←' '←']
['' '↑' '↑' '↑' '←' '←' '↑' '↑' '←' '←' '←' '←']
['' '↖' '↑' '↑' '←' '↖' '←' '↑' '←' '←' '←' '↖']
['' '↑' '↖' '↑' '←' '↑' '↖' '←' '←' '←' '←' '↑']
['' '↑' '↑' '↖' '←' '↑' '↑' '↖' '←' '←' '←' '←']]
最长子字符串为: CSACSA