🔗 🔴 3995. Minimum Cost to Convert String III

Problem Statement

題目簡述

給定等長字串 source\textit{source} 與 target\textit{target},以及若干組等長的「模式、替換字串」規則 rules[k]=[patternk,replacementk]\textit{rules}[k] = [\textit{pattern}_k, \textit{replacement}_k] 與對應基礎成本 costs[k]\textit{costs}[k]。
任意規則皆可套用任意次數:模式中的 * 可匹配任意字元,每次套用的成本為 costs[k]\textit{costs}[k] 加上 patternk\textit{pattern}_k 中的 * 數量,且每個字元位置最多只能被規則使用一次。求將 source\textit{source} 轉換成 target\textit{target} 的最小總成本;若無法完成則回傳 −1-1。

Constraints

約束條件

  • 1≤∣source∣=∣target∣≤50001 \le |\textit{source}| = |\textit{target}| \le 5000
  • source\textit{source} 與 target\textit{target} 僅包含小寫英文字母
  • 1≤∣rules∣=∣costs∣≤2001 \le |\textit{rules}| = |\textit{costs}| \le 200
  • 1≤∣patternk∣=∣replacementk∣≤201 \le |\textit{pattern}_k| = |\textit{replacement}_k| \le 20
  • 每個 patternk\textit{pattern}_k 至少包含一個小寫英文字母,且至多包含 55 個 *
  • 每個 replacementk\textit{replacement}_k 僅包含小寫英文字母
  • 1≤costs[k]≤10001 \le \textit{costs}[k] \le 1000

思路:劃分型 DP

因為每個字元位置最多只能被套用一次規則,且替換前後長度不變,所有被選中的操作區間彼此不重疊,而且套用規則後該區間就會直接定型為目標子字串。這讓整個轉換過程可以由左到右拆成互不重疊的段落,屬於標準的 劃分型DP(Partition DP)。

首先進行預處理:將每條規則的 * 個數直接加進 costs[k]\textit{costs}[k],令 wk=costs[k]+count⁡(patternk,’*’)w_k = \textit{costs}[k] + \operatorname{count}(\textit{pattern}_k, \texttt{'*'}) 為該規則的實際總成本,並記 mk=∣patternk∣m_k = |\textit{pattern}_k|,避免在轉移過程中重複計算。

狀態定義與轉移

設 n=∣source∣n = |\textit{source}|,定義狀態 f(i)f(i) 表示將後綴 source[i…n−1]\textit{source}[i \dots n - 1] 轉換成 target[i…n−1]\textit{target}[i \dots n - 1] 所需的最小總成本(若無法轉換則為 +∞+\infty)。

  • 初始條件(邊界狀態):

    f(n)=0f(n) = 0

    表示空後綴不需任何成本。

  • 轉移方程:站在位置 ii 時,有兩類決策:

    1. 不套用規則:若 source[i]=target[i]\textit{source}[i] = \textit{target}[i],可以保留該位置不變,直接轉移至 f(i+1)f(i + 1)。
    2. 套用第 kk 條規則:檢查規則 (patternk,replacementk)(\textit{pattern}_k, \textit{replacement}_k) 是否能在位置 ii 完成 字串匹配(String Matching)——即滿足 i+mk≤ni + m_k \le n、target[i…i+mk−1]=replacementk\textit{target}[i \dots i + m_k - 1] = \textit{replacement}_k,且對所有 0≤j<mk0 \le j < m_k 皆有 patternk[j]=’*’\textit{pattern}_k[j] = \texttt{'*'} 或 patternk[j]=source[i+j]\textit{pattern}_k[j] = \textit{source}[i + j]。若匹配成功,支付成本 wkw_k 並轉移至 f(i+mk)f(i + m_k)。

    記符合上述匹配條件的規則集合為 M(i)\mathcal{M}(i),則:

    f(i)=min⁡(cskip(i),  min⁡k∈M(i)(wk+f(i+mk))),cskip(i)={f(i+1),if source[i]=target[i],+∞,otherwise.f(i) = \min\Bigl( c_{\text{skip}}(i),\; \min_{k \in \mathcal{M}(i)} \bigl(w_k + f(i + m_k)\bigr) \Bigr), \quad c_{\text{skip}}(i) = \begin{cases} f(i + 1), & \text{if } \textit{source}[i] = \textit{target}[i], \\ +\infty, & \text{otherwise}. \end{cases}

  • 最終答案:若 f(0)=+∞f(0) = +\infty 則無解回傳 −1-1,否則回傳 f(0)f(0)。

實作上以 記憶化搜尋(Memoization) 計算 f(0)f(0);枚舉規則時先比對 replacementk\textit{replacement}_k 與 target[i…i+mk−1]\textit{target}[i \dots i + m_k - 1],不符即可立即跳過,減少逐字比對萬用字元的次數。

複雜度分析

  • 時間複雜度:O(nRL)\mathcal{O}(n R L),其中 n=∣source∣n = |\textit{source}|,R=∣rules∣R = |\textit{rules}|,L=max⁡k∣patternk∣≤20L = \max_k |\textit{pattern}_k| \le 20。共有 nn 個狀態,每個狀態至多檢查 RR 條規則,每條規則匹配需 O(L)\mathcal{O}(L) 時間。
  • 空間複雜度:O(n)\mathcal{O}(n),用於記憶化搜尋的快取與遞迴堆疊。

Code

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
27
class Solution:
def minCost(self, source: str, target: str, rules: list[list[str]], costs: list[int]) -> int:
n = len(source)

for i, (pattern, _) in enumerate(rules):
costs[i] += pattern.count("*")

@cache
def dfs(i: int) -> int:
if i == n:
return 0

res = inf if source[i] != target[i] else dfs(i + 1)
for (pattern, replacement), cost in zip(rules, costs):
m = len(pattern)
if i + m > n or replacement != target[i : i + m]:
continue
for j, ch in enumerate(pattern):
if ch != "*" and ch != source[i + j]:
break
else:
res = min(res, cost + dfs(i + m))
return res

ans = dfs(0)
dfs.cache_clear()
return ans if ans != inf else -1

寫在最後

Cover Image Credit

The cover image was created by @Shacola. All rights belong to the original artist.

If you are the copyright holder and believe this usage is inappropriate, please contact me by email or leave a comment. I will remove the image promptly.