题目
分析
看到两个字符串就想到用动态规划来做这道题了。设dp[i][j]为text1[:i]和text2[:j]的最长公共子序列的长度。
如果计算dp[i][j]分为两种情况:
- 1,当text1[i-1]==text2[j-1]时,此时两个字符串的对应字符相同,所以长度在原来都没这两个字符的基础上+1:dp[i][j]=dp[i-1][j-1]+1
- 2, 当text1[i-1]!=text2[j-1]时,此时两个字符串对应的字符不同,那么延续dp[i][j-1]和dp[i-1][j]的最大值。
python代码
class Solution(object):
def longestCommonSubsequence(self, text1, text2):
"""
:type text1: str
:type text2: str
:rtype: int
"""
m,n = len(text1),len(text2)
dp = [[0]*(n+1) for i in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
if text1[i-1]==text2[j-1]:
dp[i][j] = dp[i-1][j-1]+1
else:
dp[i][j] = max(dp[i-1][j],dp[i][j-1])
return dp[-1][-1]