Can Convert String in K Moves LeetCode solution in JavaScript

1
/**
2
* @param {string} s
3
* @param {string} t
4
* @param {number} k
5
* @return {boolean}
6
*/
7
var canConvertString = function (s, t, k) {
8
let res = true;
9
if (s.length === t.length) {
10
let tmp = [];
11
let countMap = new Map();
12
for (let i = 0; i < s.length; i++) {
13
let n1 = s[i].charCodeAt();
14
let n2 = t[i].charCodeAt();
15
let r = n2 - n1;
16
if (r < 0) {
17
r += 26;
18
}
19
// exclude special case 0
20
if (r > 0) {
21
// Considering repeated letters, the unrepeated move should change to r + 26*n (n>=0)
22
// use hash table to count the same letter
23
if (!countMap.has(r)) {
24
// first time to move
25
countMap.set(r, 1);
26
tmp.push(r);
27
} else {
28
// n time to move, n means the count of the same letter
29
let c = countMap.get(r);
30
tmp.push(r + c * 26);
31
// update count
32
countMap.set(r, c + 1);
33
}
34
}
35
}
36
// check all possible move in range
37
for (let i = 0; i < tmp.length; i++) {
38
let t = tmp[i];
39
if (t > k) {
40
res = false;
41
break;
42
}
43
}
44
} else {
45
res = false;
46
}
47

48
return res;
49
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0