假设我们有三个字符串s1,s2和s3,我们必须找到它们最长的公共子序列的长度。
因此,如果输入像s1 =“ ababchemxde” s2 =“ pyakcimde” s3 =“ oauctime”,则输出将为4,因为最长的公共子序列为“ acme”。
让我们看下面的实现以更好地理解-
class Solution: def solve(self, s1, s2, s3): m = len(s1) n = len(s2) o = len(s3) dp = [[[0 for i in range(o + 1)] for j in range(n + 1)] for k in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): for k in range(1, o + 1): if s1[i - 1] == s2[j - 1] == s3[k - 1]: dp[i][j][k] = 1 + dp[i - 1][j - 1][k - 1] else: dp[i][j][k] = max(dp[i - 1][j][k], dp[i][j - 1][k], dp[i][j][k - 1]) return dp[m][n][o] ob = Solution() s1 = "ababchemxde" s2 = "pyakcimde" s3 = "oauctime" print(ob.solve(s1, s2, s3))
"ababchemxde", "pyakcimde", "oauctime"输出结果
4