|
| 1 | +/** |
| 2 | + * 2976. Minimum Cost to Convert String I |
| 3 | + * https://leetcode.com/problems/minimum-cost-to-convert-string-i/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given two 0-indexed strings source and target, both of length n and consisting of |
| 7 | + * lowercase English letters. You are also given two 0-indexed character arrays original and |
| 8 | + * changed, and an integer array cost, where cost[i] represents the cost of changing the character |
| 9 | + * original[i] to the character changed[i]. |
| 10 | + * |
| 11 | + * You start with the string source. In one operation, you can pick a character x from the string |
| 12 | + * and change it to the character y at a cost of z if there exists any index j such that |
| 13 | + * cost[j] == z, original[j] == x, and changed[j] == y. |
| 14 | + * |
| 15 | + * Return the minimum cost to convert the string source to the string target using any number of |
| 16 | + * operations. If it is impossible to convert source to target, return -1. |
| 17 | + * |
| 18 | + * Note that there may exist indices i, j such that original[j] == original[i] and |
| 19 | + * changed[j] == changed[i]. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {string} source |
| 24 | + * @param {string} target |
| 25 | + * @param {character[]} original |
| 26 | + * @param {character[]} changed |
| 27 | + * @param {number[]} cost |
| 28 | + * @return {number} |
| 29 | + */ |
| 30 | +var minimumCost = function(source, target, original, changed, cost) { |
| 31 | + const graph = new Array(26).fill().map(() => new Array(26).fill(Infinity)); |
| 32 | + for (let i = 0; i < 26; i++) graph[i][i] = 0; |
| 33 | + |
| 34 | + for (let i = 0; i < original.length; i++) { |
| 35 | + const from = original[i].charCodeAt(0) - 97; |
| 36 | + const to = changed[i].charCodeAt(0) - 97; |
| 37 | + graph[from][to] = Math.min(graph[from][to], cost[i]); |
| 38 | + } |
| 39 | + |
| 40 | + for (let k = 0; k < 26; k++) { |
| 41 | + for (let i = 0; i < 26; i++) { |
| 42 | + for (let j = 0; j < 26; j++) { |
| 43 | + graph[i][j] = Math.min(graph[i][j], graph[i][k] + graph[k][j]); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + let result = 0; |
| 49 | + for (let i = 0; i < source.length; i++) { |
| 50 | + if (source[i] !== target[i]) { |
| 51 | + const from = source[i].charCodeAt(0) - 97; |
| 52 | + const to = target[i].charCodeAt(0) - 97; |
| 53 | + if (graph[from][to] === Infinity) return -1; |
| 54 | + result += graph[from][to]; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return result; |
| 59 | +}; |
0 commit comments