Skip to content

Commit cb03069

Browse files
authored
Create 1638-count-substrings-that-differ-by-one-character.js
1 parent de5b02c commit cb03069

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @param {string} s
3+
* @param {string} t
4+
* @return {number}
5+
*/
6+
const countSubstrings = function (s, t) {
7+
const m = s.length
8+
const n = t.length
9+
const matrix = (m, n, v) => Array.from({ length: m }, () => Array(n).fill(v))
10+
// number of exact same substrings ending at s[i] and t[j].
11+
const same = matrix(m + 1, n + 1, 0)
12+
// number of substrings having 1 different character ending at s[i] and t[j].
13+
const one = matrix(m + 1, n + 1, 0)
14+
let result = 0
15+
for (let i = 1; i <= m; ++i) {
16+
for (let j = 1; j <= n; ++j) {
17+
if (s[i - 1] == t[j - 1]) {
18+
same[i][j] = same[i - 1][j - 1] + 1
19+
one[i][j] = one[i - 1][j - 1]
20+
} else {
21+
one[i][j] = same[i - 1][j - 1] + 1
22+
}
23+
result += one[i][j]
24+
}
25+
}
26+
return result
27+
}

0 commit comments

Comments
 (0)