定义:
两个字符串共有的最长的子序列(可不连续),最长公共字符串(Longest CommonSubstring)是两个字符串共有的最长的连续字符串。
方法:穷举法,动态规划
动态规划法的简介:
《后补》
代码思路:
《后补》
Python 代码:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
from random import randint
#generate a unsorted list
origin = []
LETTERS="abcdefghijklmnopqrstuvwxyz"
def randomList():
strs = ""
end = randint(5,10)
for i in xrange(0,end,1):
strs += LETTERS[randint(0,25)]
return strs
def lcs(getRandomStr):
stra = getRandomStr()
strb = getRandomStr()
la = len(stra)
lb = len(strb)
c = [[0]*(lb+1) for i in range(la+1)]
print stra
print strb
for i in range(la-1,-1,-1):
for j in range(lb-1,-1,-1):
if stra[i] == strb[j]:
c[i][j] = c[i+1][j+1] + 1
else:
c[i][j] = max({c[i+1][j],c[i][j+1]})
#print the result
i,j = 0,0
ret = ''
while i < la and j < lb:
# print i,j
if stra[i] == strb[j]:
ret += stra[i]
i += 1
j += 1
elif c[i+1][j] >= c[i][j+1] :
i += 1
else:
j += 1
print ret
if __name__ == '__main__':
lcs(randomList)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。