Count Binary Substrings LeetCode solution in JavaScript

1
/**
2
* find all bit switches '01' and '10'.
3
* From each one expand sideways: i goes left, j goes right
4
* Until:
5
* if '01' -> i,j != 0,1
6
* if '10' -> i,j != 1,0
7
* and within input boundaries
8
*/
9
var countBinarySubstrings = function (s) {
10
let i = 0;
11
const n = s.length;
12
let count = 0;
13
while (i < n - 1) {
14
if (s[i] != s[i + 1]) {
15
if (s[i] === "0") {
16
count += countZeroOnes(s, i, true);
17
} else {
18
count += countZeroOnes(s, i, false);
19
}
20
}
21
i++;
22
}
23
return count;
24

25
// count the number of valid substrings substrings
26
function countZeroOnes(s, start, startsWithZero) {
27
let count = 0;
28
let i = start;
29
let j = start + 1;
30
const n = s.length;
31
if (startsWithZero) {
32
while (i >= 0 && j < n && s[i] === "0" && s[j] === "1") {
33
count++;
34
i--;
35
j++;
36
}
37
} else {
38
while (i >= 0 && j < n && s[i] === "1" && s[j] === "0") {
39
count++;
40
i--;
41
j++;
42
}
43
}
44
return count;
45
}
46
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0