Number of Ways to Select Buildings LeetCode solution in C++

1
class Solution {
2
public:
3
long long numberOfWays(string s) {
4
long long a = 0, b = 0,
5
ans = 0; // a and b are the number of occurances of '1' and '0'
6
// after the current building respectively.
7
for (int i = 0; i < s.length(); i++) {
8
if (s[i] == '1')
9
a++;
10
else
11
b++;
12
}
13
long long c = 0, d = 0; // c and d are the number of occurances of '1' and
14
// '0' before the current building respectively.
15
for (int i = 0; i < s.length(); i++) {
16
if (s[i] == '1') { // Counting the sequences of "010"
17
ans += (d * b);
18
a--;
19
c++;
20
} else { // Counting the sequences of "101"
21
ans += (a * c);
22
b--;
23
d++;
24
}
25
}
26
return ans;
27
}
28
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0