Minimum Distance to Type a Word Using Two Fingers LeetCode solution in JavaScript

1
const dist = function (from, to) {
2
if (from == -1) return 0;
3
const d1 = Math.abs(
4
((from.charCodeAt(0) - 65) % 6) - ((to.charCodeAt(0) - 65) % 6)
5
),
6
d2 = Math.abs(
7
Math.floor((from.charCodeAt(0) - 65) / 6) -
8
Math.floor((to.charCodeAt(0) - 65) / 6)
9
);
10
return d1 + d2;
11
};
12
var minimumDistance = function (word) {
13
const dp = new Map();
14

15
const dfs = function (i, lpos, rpos) {
16
if (i == word.length) return 0;
17
const key = [i, lpos, rpos].join(",");
18
if (dp.get(key)) return dp.get(key);
19
dp.set(
20
key,
21
Math.min(
22
dist(lpos, word[i]) + dfs(i + 1, word[i], rpos),
23
dist(rpos, word[i]) + dfs(i + 1, lpos, word[i])
24
)
25
);
26
return dp.get(key);
27
};
28
return dfs(0, -1, -1);
29
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0