|
| 1 | +/** |
| 2 | + * 1320. Minimum Distance to Type a Word Using Two Fingers |
| 3 | + * https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter |
| 7 | + * is located at some coordinate. |
| 8 | + * |
| 9 | + * For example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at |
| 10 | + * coordinate (0, 1), the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located |
| 11 | + * at coordinate (4, 1). |
| 12 | + * |
| 13 | + * Given the string word, return the minimum total distance to type such string using only two |
| 14 | + * fingers. |
| 15 | + * |
| 16 | + * The distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|. |
| 17 | + * |
| 18 | + * Note that the initial positions of your two fingers are considered free so do not count towards |
| 19 | + * your total distance, also your two fingers do not have to start at the first letter or the first |
| 20 | + * two letters. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {string} word |
| 25 | + * @return {number} |
| 26 | + */ |
| 27 | +var minimumDistance = function(word) { |
| 28 | + const memo = {}; |
| 29 | + return dp(0, null, null); |
| 30 | + |
| 31 | + function dp(index, finger1, finger2) { |
| 32 | + if (index === word.length) return 0; |
| 33 | + |
| 34 | + const key = `${index},${finger1},${finger2}`; |
| 35 | + if (memo[key] !== undefined) return memo[key]; |
| 36 | + |
| 37 | + const nextChar = word[index]; |
| 38 | + const moveFinger1 = distance(finger1, nextChar) + dp(index + 1, nextChar, finger2); |
| 39 | + const moveFinger2 = distance(finger2, nextChar) + dp(index + 1, finger1, nextChar); |
| 40 | + |
| 41 | + memo[key] = Math.min(moveFinger1, moveFinger2); |
| 42 | + return memo[key]; |
| 43 | + } |
| 44 | + |
| 45 | + function getPosition(char) { |
| 46 | + const code = char.charCodeAt(0) - 65; |
| 47 | + return [Math.floor(code / 6), code % 6]; |
| 48 | + } |
| 49 | + |
| 50 | + function distance(from, to) { |
| 51 | + if (from === null) return 0; |
| 52 | + const [x1, y1] = getPosition(from); |
| 53 | + const [x2, y2] = getPosition(to); |
| 54 | + return Math.abs(x1 - x2) + Math.abs(y1 - y2); |
| 55 | + } |
| 56 | +}; |
0 commit comments