The longest common substring is required to be continuous in the original string, and the subsequence only needs to keep the relative order consistent, not continuous.
Let me share the dp method, the time complexity is O(mn), the space complexity is O(mn)
class Solution:
def lcs(self,s1,s2):
max_len=0
max_index=0
m=len(s1)
n=len(s2)
dp=[[0]*(n+1) for i in range(m+1)]
for i in range(m+1):
for j in range(n+1):
if(i==0 or j==0):
continue
elif(s1[i-1]==s2[j-1]):
dp[i][j]=dp[i-1][j-1]+1
if(dp[i][j]>max_len):
max_len=dp[i][j]
max_index=i-max_len
return max_len,max_index,s1[max_index:max_index+max_len]
if __name__=="__main__":
solution=Solution()
s1='acbac'
s2='acaccbabb'
max_len,max_index,seq=solution.lcs(s1,s2)
print(max_len,max_index,seq)
Those who are interested can help me find bugs. I don’t think there is any problem. If you can find bugs for me, thank you very much, hahaha
references
[1]. Algorithm design-LCS longest common subsequence&& longest common substring&&LIS longest increasing subsequence. https://blog.csdn.net/sushauai/article/details/50118073
[2]. The longest common substring and the longest common subsequence. https://www.cnblogs.com/fengziwei/p/7827959.html