假设我们有两个字符串s和t。我们必须找到同时包含s和t作为子序列的最短字符串的长度。
因此,如果输入像s =“ pipe” t =“ people”,则输出将为7,因为一个可能的超序列是“ pieople”。
让我们看下面的实现以更好地理解-
class Solution: def solve(self, s, t): m = len(s) n = len(t) table = [[0 for i in range(n + 1)] for j in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: table[i][j] = 0 else: if s[i - 1] == t[j - 1]: table[i][j] = 1 + table[i - 1][j - 1] else: table[i][j] = max(table[i][j - 1], table[i - 1][j]) return m + n - table[m][n] ob = Solution() s = "pipe" t = "people" print(ob.solve(s, t))
"pipe", "people"输出结果
7