在Python中找到子序列数量的最小值,这些子序列的连接与目标相同
假设我们有两个字符串 source 和 target,我们必须找到我们可以形成的源的最小子序列数量,以便如果将它们连接起来,它将与目标相同。如果没有这样的结果,则返回-1。
因此,如果输入为 source =“ xyz ”target =“ xyzyzz”,则输出将为3,因为我们可以将这些子序列连接起来[“xyz”+”yz”+”z”]
为了解决这个问题,我们将遵循以下步骤:
- s_size:s的大小,t_size:t的大小
- concat_count:0,target_idx:0
- while target_idx < t_size,do
- source_idx: = 0
- temp_index: = target_idx
- while source_idx < s_size and target_idx < t_size,do
- if s[source_idx]与t[target_idx]相同,则
- target_idx:= target_idx + 1
- source_idx:= source_idx + 1
- if temp_index与target_idx相同,则
- 返回-1
- concat_count:= concat_count + 1
- 返回concat_count
让我们看一下以下实现,以更好地理解