调试中...
调试中...
题目描述
题目描述
题解
题解
提交记录
提交记录
代码
代码
测试用例
测试用例
测试结果
测试结果
困难
相关标签
相关企业
提示

给你一个字符串数组 words 和一个字符串 target

如果字符串 xwords 任意 字符串的 ,则认为 x 是一个 有效 字符串。

现计划通过 连接 有效字符串形成 target ,请你计算并返回需要连接的 最少 字符串数量。如果无法通过这种方式形成 target,则返回 -1

 

示例 1:

输入: words = ["abc","aaaaa","bcdef"], target = "aabcdabc"

输出: 3

解释:

target 字符串可以通过连接以下有效字符串形成:

  • words[1] 的长度为 2 的前缀,即 "aa"
  • words[2] 的长度为 3 的前缀,即 "bcd"
  • words[0] 的长度为 3 的前缀,即 "abc"

示例 2:

输入: words = ["abababab","ab"], target = "ababaababa"

输出: 2

解释:

target 字符串可以通过连接以下有效字符串形成:

  • words[0] 的长度为 5 的前缀,即 "ababa"
  • words[0] 的长度为 5 的前缀,即 "ababa"

示例 3:

输入: words = ["abcdef"], target = "xyz"

输出: -1

 

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 5 * 104
  • 输入确保 sum(words[i].length) <= 105.
  • words[i]  只包含小写英文字母。
  • 1 <= target.length <= 5 * 104
  • target  只包含小写英文字母。
通过次数
9.8K
提交次数
16.8K
通过率
58.3%


相关企业

提示 1
Let dp[i] be the minimum cost to form the prefix of length i of target.

提示 2
Use Rabin-Karp to hash every prefix and store it in a HashSet.

提示 3
Use Binary search to find the longest substring starting at index i (target[i..j]) that has a hash present in the HashSet.

提示 4
Inverse Modulo precomputation can optimise hash calculation.

提示 5
Use Lazy Segment Tree, or basic Segment Tree to update dp[i..j].

提示 6
Is it possible to use two TreeSets to update dp[i..j]?


评论 (0)

贡献者
© 2025 领扣网络(上海)有限公司
0 人在线
行 1,列 1
运行和提交代码需要登录
words =
["abc","aaaaa","bcdef"]
target =
"aabcdabc"
Source