Number of Ways to Select Buildings LeetCode solution in Java

1
class Solution {
2
public long numberOfWays(String s) {
3
int zero = 0; // Individual zeroes count
4
long zeroOne = 0; // Number of combinations of 01s
5
int one = 0; // Individual ones count
6
long oneZero = 0; // Number of combinations of 10s
7
long tot = 0; // Final answer
8
for (char ch : s.toCharArray()) {
9
if (ch == '0') {
10
zero++;
11
if (one > 0)
12
oneZero +=
13
one; // Each of the previously found 1s can pair up with the current 0 to form 10
14
if (zeroOne > 0)
15
tot +=
16
zeroOne; // Each of the previously formed 01 can form a triplet with the current 0 to
17
// form 010
18
} else {
19
one++;
20
if (zero > 0) zeroOne += zero; // Each of the previously found 0s can pair to form 01
21
if (oneZero > 0) tot += oneZero; // Each of the previously formed 10 can form 101
22
}
23
}
24
return tot;
25
}
26
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0