# 最长公共子串

X=<x1,x2,x3......xn> ,Y=<y1,y2,y3......yn>

`record[i][j] = record[i-1][j-1]+1`
i,j表示以xi和yj结尾的最长公共子串，具体代码如下：

``````class Solution:
def LongestCommonSubstring(self,text,query):
record = [[0 for i in range(len(query)+1)] for j in range(len(text)+1)]
record[0][0]=0
res,index = 0,0
for i in range(0,len(text)):
for j in range(0,len(query)):
if text[i]==query[j]:
record[i][j] = record[i-1][j-1]+1
else:
record[i][j] = 0
if res<record[i][j]:
res=record[i][j]
index=i
return res,text[index-res+1:index+1]

if __name__ =="__main__":
s = Solution()
text,query = "acaccbabb","acbac"
print s.LongestCommonSubstring(text,query)
``````

``````class Solution:
def LongestCommonSubstring(self,text,query):
record = [0 for i in range(len(text)+1)]
res,index = 0,0
for i in range(len(query)):
for j in range(len(text)-1,0,-1):
if query[i]==text[j]:
record[j] = record[j-1]+1
else:
record[j] = 0
if res<record[j]:
res=record[j]
index=j
return res,text[index-res+1:index+1]

if __name__ =="__main__":
s = Solution()
text,query = "acaccbabb","acbac"
print s.LongestCommonSubstring(text,query)
``````

# 最长公共子序列

``````         if text[i-1]==query[j-1]:
record[i][j]=record[i-1][j-1]+1
else:
record[i][j] = max(record[i-1][j],record[i][j-1])
``````

``````class Solution:
def LongestCommonSubSequeence(self,text,query):
record = [[0 for j in range(len(query)+1)] for i in range(len(text)+1)]
for i in range(len(text)+1):
record[i][0] = 0
for j in range(len(query)+1):
record[0][j] = 0
for i in range(1,len(text)+1):
for j in range(1,len(query)+1):
if text[i-1]==query[j-1]:
record[i][j]=record[i-1][j-1]+1
else:
record[i][j] = max(record[i-1][j],record[i][j-1])
return record[len(text)][len(query)]

if __name__ =="__main__":
s = Solution()
text,query = "acaccbabb","acbac"
print s.LongestCommonSubSequeence(text,query)
``````