軟件安全的一個小實驗,正好復習一下LCS的寫法。
實現LCS的算法和算法導論上的方式基本一致,都是先建好兩個表,一個存儲在(i,j)處當前最長公共子序列長度,另一個存儲在(i,j)處的回溯方向。
相對於算法導論的版本,增加了一個多分支回溯,即存儲回溯方向時出現了向上向左都可以的情況時,這時候就代表可能有多個最長公共子序列。當回溯到這里時,讓程序帶着存儲已經回溯的字符串的棧進行遞歸求解,當走到左上角的時候輸出出來
# coding=utf-8
class LCS():
def input(self, x, y):
#讀入待匹配的兩個字符串
if type(x) != str or type(y) != str:
print 'input error'
return None
self.x = x
self.y = y
def Compute_LCS(self):
xlength = len(self.x)
ylength = len(self.y)
self.direction_list = [None] * xlength #這個二維列表存着回溯方向
for i in xrange(xlength):
self.direction_list[i] = [None] * ylength
self.lcslength_list = [None] * (xlength + 1)
#這個二維列表存着當前最長公共子序列長度
for j in xrange(xlength + 1):
self.lcslength_list[j] = [None] * (ylength + 1)
for i in xrange(0, xlength + 1):
self.lcslength_list[i][0] = 0
for j in xrange(0, ylength + 1):
self.lcslength_list[0][j] = 0
#下面是進行回溯方向和長度表的賦值
for i in xrange(1, xlength + 1):
for j in xrange(1, ylength + 1):
if self.x[i - 1] == self.y[j - 1]:
self.lcslength_list[i][j] = self.lcslength_list[i - 1][j - 1] + 1
self.direction_list[i - 1][j - 1] = 0 # 左上
elif self.lcslength_list[i - 1][j] > self.lcslength_list[i][j - 1]:
self.lcslength_list[i][j] = self.lcslength_list[i - 1][j]
self.direction_list[i - 1][j - 1] = 1 # 上
elif self.lcslength_list[i - 1][j] < self.lcslength_list[i][j - 1]:
self.lcslength_list[i][j] = self.lcslength_list[i][j - 1]
self.direction_list[i - 1][j - 1] = -1 # 左
else:
self.lcslength_list[i][j] = self.lcslength_list[i - 1][j]
self.direction_list[i - 1][j - 1] = 2 # 左或上
self.lcslength = self.lcslength_list[-1][-1]
return self.direction_list, self.lcslength_list
def printLCS(self, curlen, i, j, s):
if i == 0 or j == 0:
return None
if self.direction_list[i - 1][j - 1] == 0:
if curlen == self.lcslength:
s += self.x[i - 1]
for i in range(len(s)-1,-1,-1):
print s[i],
print '\n'
elif curlen < self.lcslength:
s += self.x[i-1]
self.printLCS(curlen + 1, i - 1, j - 1, s)
elif self.direction_list[i - 1][j - 1] == 1:
self.printLCS(curlen,i - 1, j,s)
elif self.direction_list[i - 1][j - 1] == -1:
self.printLCS(curlen,i, j - 1,s)
else:
self.printLCS(curlen,i - 1, j,s)
self.printLCS(curlen,i, j - 1,s)
def returnLCS(self):
#回溯的入口
self.printLCS(1,len(self.x), len(self.y),'')
if __name__ == '__main__':
p = LCS()
p.input('abcbdab', 'bdcaba')
p.Compute_LCS()
p.returnLCS()
在對'abcbdab'和'bdcaba'兩個串用LCS后,得到下面結果: