LeetCode 题解工作台

最小代价构造字符串

给你一个字符串 target 、一个字符串数组 words 以及一个整数数组 costs ,这两个数组长度相同。 设想一个空字符串 s 。 你可以执行以下操作任意次数(包括 零 次): 选择一个在范围 [0, words.length - 1] 的索引 i 。 将 words[i] 追加到 s 。 …

category

4

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

困难 · 状态·转移·动态规划

bolt

答案摘要

我们定义 表示构造 前 个字符的最小代价,初始时 $f[0] = 0$,其余值均为无穷大。答案为 ,其中 是 的长度。 对于当前 ,考虑枚举单词的长度 ,如果 $j \leq i$,那么我们可以考虑从 $i - j + 1$ 到 这段区间的哈希值,如果这个哈希值对应的单词存在,那么我们可以转移从 $f[i - j]$ 转移到 。状态转移方程如下:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 target、一个字符串数组 words 以及一个整数数组 costs,这两个数组长度相同。

设想一个空字符串 s

你可以执行以下操作任意次数(包括 零 次):

  • 选择一个在范围  [0, words.length - 1] 的索引 i
  • words[i] 追加到 s
  • 该操作的成本是 costs[i]

返回使 s 等于 target最小 成本。如果不可能,返回 -1

 

示例 1:

输入: target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5]

输出: 7

解释:

  • 选择索引 1 并以成本 1 将 "abc" 追加到 s,得到 s = "abc"
  • 选择索引 2 并以成本 1 将 "d" 追加到 s,得到 s = "abcd"
  • 选择索引 4 并以成本 5 将 "ef" 追加到 s,得到 s = "abcdef"

示例 2:

输入: target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100]

输出: -1

解释:

无法使 s 等于 target,因此返回 -1。

 

提示:

  • 1 <= target.length <= 5 * 104
  • 1 <= words.length == costs.length <= 5 * 104
  • 1 <= words[i].length <= target.length
  • 所有 words[i].length 的总和小于或等于 5 * 104
  • targetwords[i] 仅由小写英文字母组成。
  • 1 <= costs[i] <= 104
lightbulb

解题思路

方法一:字符串哈希 + 动态规划 + 枚举长度

我们定义 f[i]f[i] 表示构造 target\textit{target}ii 个字符的最小代价,初始时 f[0]=0f[0] = 0,其余值均为无穷大。答案为 f[n]f[n],其中 nntarget\textit{target} 的长度。

对于当前 f[i]f[i],考虑枚举单词的长度 jj,如果 jij \leq i,那么我们可以考虑从 ij+1i - j + 1ii 这段区间的哈希值,如果这个哈希值对应的单词存在,那么我们可以转移从 f[ij]f[i - j] 转移到 f[i]f[i]。状态转移方程如下:

f[i]=min(f[i],f[ij]+cost[k])f[i] = \min(f[i], f[i - j] + \textit{cost}[k])

其中 cost[k]\textit{cost}[k] 表示长度为 jj 的单词且哈希值与 target[ij+1,i]\textit{target}[i - j + 1, i] 相同的单词的最小代价。

时间复杂度 O(n×L)O(n \times \sqrt{L}),空间复杂度 O(n)O(n)。其中 nntarget\textit{target} 的长度,而 LL 是数组 words\textit{words} 中所有单词的长度之和。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
    def minimumCost(self, target: str, words: List[str], costs: List[int]) -> int:
        base, mod = 13331, 998244353
        n = len(target)
        h = [0] * (n + 1)
        p = [1] * (n + 1)
        for i, c in enumerate(target, 1):
            h[i] = (h[i - 1] * base + ord(c)) % mod
            p[i] = (p[i - 1] * base) % mod
        f = [0] + [inf] * n
        ss = sorted(set(map(len, words)))
        d = defaultdict(lambda: inf)
        min = lambda a, b: a if a < b else b
        for w, c in zip(words, costs):
            x = 0
            for ch in w:
                x = (x * base + ord(ch)) % mod
            d[x] = min(d[x], c)
        for i in range(1, n + 1):
            for j in ss:
                if j > i:
                    break
                x = (h[i] - h[i - j] * p[j]) % mod
                f[i] = min(f[i], f[i - j] + d[x])
        return f[n] if f[n] < inf else -1
speed

复杂度分析

指标
时间complexity is O(N * M) in the worst case where N is target length and M is total sum of words length, optimized by efficient word matching. Space complexity is O(N) for the DP array plus additional structures for string matching.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check for overlapping word matches that could reduce total cost.

  • question_mark

    Notice when certain prefixes cannot be completed, signaling a -1 result.

  • question_mark

    Expect usage of hashing or trie-based structures to manage many word transitions.

warning

常见陷阱

外企场景
  • error

    Failing to reuse words correctly leading to higher cost than necessary.

  • error

    Ignoring the order of words causing invalid string construction.

  • error

    Inefficient substring matching causing TLE on large input sizes.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Change costs array to allow negative values and require handling minimal net cost.

  • arrow_right_alt

    Restrict each word to be used at most once and compute the minimal cost.

  • arrow_right_alt

    Find all possible minimal cost sequences instead of just the total minimal cost.

help

常见问题

外企场景

最小代价构造字符串题解:状态·转移·动态规划 | LeetCode #3213 困难