Count Substrings That Differ by One Character LeetCode solution in JavaScript

1
var countSubstrings = function (s, t) {
2
const count1 = countAllSubstr(s);
3
const count2 = countAllSubstr(t);
4

5
let res = 0;
6

7
for (const [substr1, freq1] of count1) {
8
for (const [substr2, freq2] of count2) {
9
if (differByOneChar(substr1, substr2)) {
10
res += freq1 * freq2;
11
}
12
}
13
}
14

15
return res;
16

17
function countAllSubstr(str) {
18
const n = str.length;
19
const count = new Map();
20

21
for (let i = 0; i < n; i++) {
22
let substr = "";
23
for (let j = i; j < n; j++) {
24
substr += str.charAt(j);
25

26
if (!count.has(substr)) count.set(substr, 0);
27
count.set(substr, count.get(substr) + 1);
28
}
29
}
30

31
return count;
32
}
33

34
function differByOneChar(str1, str2) {
35
if (str1.length != str2.length) return false;
36

37
const n = str1.length;
38

39
let missed = 0;
40

41
for (let i = 0; i < n; i++) {
42
const char1 = str1.charAt(i);
43
const char2 = str2.charAt(i);
44

45
if (char1 != char2) missed++;
46

47
if (missed > 1) return false;
48
}
49

50
return missed === 1;
51
}
52
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0