Minimum Cost to Convert String II
You are given two 0-indexed strings source and target, both of length n and consisting of lowercase English characters. You are also given two 0-indexed string arrays original and changed, and an integer array cost, where cost[i] represents the cost of converting the string original[i] to the string changed[i].
You start with the string source. In one operation, you can pick a substring x from the string, and change it to y at a cost of z if there exists any index j such that cost[j] == z, original[j] == x, and changed[j] == y. You are allowed to do any number of operations, but any pair of operations must satisfy either of these two conditions:
- The substrings picked in the operations are
source[a..b]andsource[c..d]with eitherb < cord < a. In other words, the indices picked in both operations are disjoint. - The substrings picked in the operations are
source[a..b]andsource[c..d]witha == candb == d. In other words, the indices picked in both operations are identical.
Return the minimum cost to convert the string source to the string target using any number of operations. If it is impossible to convert source to target, return -1.
Note that there may exist indices i, j such that original[j] == original[i] and changed[j] == changed[i].
source = "abcd", target = "acbe", original = ["a","b","c","c","e","d"], changed = ["b","c","b","e","b","e"], cost = [2,5,5,1,2,20]28b to c, c to e, e to b, and d to e with costs 5, 1, 2, and 20 respectively.source = "abcdefgh", target = "acdeeghh", original = ["bcd","fgh","thh"], changed = ["cde","thh","ghh"], cost = [1,3,5]9bcd to cde, then changing fgh to thh, and then thh to ghh.Constraints
- 1 <= source.length == target.length <= 1000
- source, target consist only of lowercase English characters.
- 1 <= cost.length == original.length == changed.length <= 100
- 1 <= original[i].length == changed[i].length <= source.length
- original[i], changed[i] consist only of lowercase English characters.
- original[i] != changed[i]
- 1 <= cost[i] <= 10^6