【发布时间】:2021-10-02 11:37:51
【问题描述】:
我看到了原题Minimum of subsequences required to convert one string to another,和LeetCode上的这个问题1055. Shortest Way to Form String很相似。
说明:
给定两个字符串 source 和 target,返回 source 的最小子序列数,使得它们的 串联 等于 target。如果任务不可能完成,返回-1。
示例 1:
输入:源 = "abc",目标 = "abcbc"
输出:2
说明:目标“abcbc”可以由“abc”和“bc”组成,它们是源“abc”的子序列。
假设s'是source的子序列,所以这个问题就是找到s'_1s'_2...s'_k形成target。我的问题是如何找到将一个字符串交错到另一个字符串所需的最小子序列数。
例如:
输入:source = "adbsc", target = "addsbc"
输出:2
解释:
step1: s'1 = adbc, then target' = ds
step2: s'2 = ds, then target' = ""
不知道能不能解决这个问题,把source和target'的最长公共子序列去掉,形成t',重复直到t' = ""。
这是我的代码:
class Solution:
def shortestWay(self, s: str, t: str) -> int:
def lcs(s: str, t: str) -> str:
m, n = len(s), len(t)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if s[i-1] == t[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
choose = [False] * n
i, j = m, n
while i + j != 0:
if s[i-1] == t[j-1]:
choose[j-1] = True
i, j = i - 1, j - 1
elif dp[i][j] == dp[i-1][j]:
i -= 1
elif dp[i][j] == dp[i][j-1]:
j -= 1
print(f'lcs({s}, {t}) is', ''.join(t[i] for i, v in enumerate(choose) if v))
return ''.join(t[i] for i, v in enumerate(choose) if not v)
ans = 0
while t:
ans += 1
t1 = lcs(s, t)
print(repr(t1))
if t1 == t:
return -1
t = t1
return ans
"""
lcs(adbsc, addsbc) is adbc
'ds'
lcs(adbsc, ds) is ds
''
"""
有人可以帮我证明/解决这个问题吗,谢谢!
【问题讨论】:
标签: string algorithm subsequence