Minimum Cost to Convert String III Problem
Description
LeetCode Problem 3995.
You are given two strings, source and target.
You are also given a 2D string array rules, where rules[i] = [pattern_i, replacement_i], and an integer array costs, where costs[i] is the base cost of applying rules[i]. Both arrays have the same length. Additionally, pattern_i and replacement_i have the same length.
You may apply any rule any number of times. Each rule application works as follows:
- Choose an index
lsuch that the range of positions fromltol + pattern_i.length - 1exists in the current string and none of these positions has been used in a previous rule application. - For each index
j, the characterpattern_i[j]must either be equal to the current character at positionl + j, or be'*'. - Replace the characters in this range with
replacement_i. The replacement is used exactly as given and does not contain wildcards. - The cost of this rule application is
costs[i]plus the number of'*'characters inpattern_i. - Once a character position has been used in a rule application, it cannot be used in any later rule application.
Since every pattern_i and replacement_i have the same length, character positions are preserved after every rule application.
Return the minimum total cost required to transform source into target. If it is impossible, return -1.
Example 1:
Input: source = "hello", target = "world", rules = [["he","wo"],["llo","rld"]], costs = [3,4]
Output: 7
Explanation:
- Apply rules[0] to replace "he" with "wo" at cost 3, so the string becomes "wollo".
- Apply rules[1] to replace "llo" with "rld" at cost 4, so the string becomes "world".
- The total cost is 3 + 4 = 7.
Example 2:
Input: source = "cat", target = "dog", rules = [["c*t","dog"]], costs = [2]
Output: 3
Explanation:
- Apply rules[0] to replace "cat" with "dog". The wildcard '*' matches 'a', adding 1 to the base cost 2.
- The total cost is 2 + 1 = 3.
Example 3:
Input: source = "test", target = "next", rules = [["*e*t","next"]], costs = [4]
Output: 6
Explanation:
- Apply rules[0] to replace "test" with "next". The first wildcard matches 't' and the second wildcard matches 's', adding 2 to the base cost 4.
- The total cost is 4 + 2 = 6.
Example 4:
Input: source = "ab", target = "bc", rules = [["a*","bd"]], costs = [9]
Output: -1
Explanation:
No sequence of rule applications can transform source into target, so the answer is -1.
Constraints:
1 <= source.length == target.length <= 5000sourceandtargetconsist of lowercase English letters.1 <= rules.length == costs.length <= 200rules[i] = [pattern_i, replacement_i]1 <= pattern_i.length == replacement_i.length <= 20pattern_icontains at least one lowercase English letter and at most 5'*'characters.replacement_icontains only lowercase English letters.1 <= costs[i] <= 1000
Solution
Approach: Dynamic Programming over Positions
A position that has been used by a rule can never be used again, so a rule can only match characters that are still the original ones from source. That means the rules rewrite disjoint segments of source, and the characters outside those segments stay as they are.
Let dp[i] be the minimum cost to turn source[0..i) into target[0..i), with dp[0] = 0. From position i:
- if
source[i] == target[i], we may leave the character alone:dp[i + 1] = min(dp[i + 1], dp[i]); - for every rule with pattern
pand replacementrof lengthL, ifi + L <= n,requalstarget[i..i+L), andpmatchessource[i..i+L)(each*matches any letter), thendp[i + L] = min(dp[i + L], dp[i] + cost + stars(p)).
The answer is dp[n], or -1 if it is unreachable. Checking the replacement against target first rejects most rules quickly.
Complexity: time O(n * k * L) and space O(n), where k is the number of rules and L <= 20 the maximum pattern length.
import re
class Solution:
def minCost(self, source: str, target: str, rules: List[List[str]], costs: List[int]) -> int:
n = len(source)
# "*" matches any character, so a pattern becomes a regular expression.
compiled = [
(re.compile(p.replace('*', '.')), r, c + p.count('*'))
for (p, r), c in zip(rules, costs)
]
INF = float('inf')
dp = [INF] * (n + 1)
dp[0] = 0
for i in range(n):
if dp[i] == INF:
continue
if source[i] == target[i]:
dp[i + 1] = min(dp[i + 1], dp[i])
for pattern, rep, cost in compiled:
j = i + len(rep)
if j <= n and target.startswith(rep, i) and pattern.match(source, i):
dp[j] = min(dp[j], dp[i] + cost)
return -1 if dp[n] == INF else dp[n]