Trains the technique from
LeetCode 3995Minimum Cost to Convert String IIIThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
Two tapes of equal length are given as source and target.
Each entry of rules is a pair [pattern, replacement] of equal length, and costs[i] is what that rule charges. A '*' in a pattern stands for any single letter; a replacement holds letters only.
Choose any number of stretches of source that do not overlap each other. Each chosen stretch is rewritten by one rule whose pattern matches that stretch of source and whose replacement is exactly the matching stretch of target, at that rule's cost. Every position left uncovered must already read the same on both tapes.
Return the least total cost of turning source into target, or -1 when it cannot be done.
Example 1
Rewriting each letter on its own costs 2 twice, coming to 4, while the rule covering both letters at once costs 3, so the wider rule wins.
Example 2
The only rule turns the letter into c, which is not what the target reads, so nothing can be done.
Example 3
The two tapes already read the same everywhere, so every position may be left alone and nothing needs paying for.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def min_cost(source: str, target: str, rules: list[list[str]], costs: list[int]) -> int:public int minCost(String source, String target, List<List<String>> rules, int[] costs)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.