Skip to content

Commit cc9bc5e

Browse files
authored
Create number-of-ways-to-split-a-string.cpp
1 parent c159cad commit cc9bc5e

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int numWays(string s) {
7+
static const int MOD = 1e9 + 7;
8+
int ones = count_if(cbegin(s), cend(s),
9+
[](const auto& x) {
10+
return x == '1';
11+
});
12+
if (ones % 3) {
13+
return 0;
14+
}
15+
ones /= 3;
16+
if (ones == 0) {
17+
return static_cast<int64_t>(s.length() - 1) * (s.length() - 2) / 2 % MOD;
18+
}
19+
int count = 0, left = 0, right = 0;
20+
for (const auto& c : s) {
21+
if (c == '1') {
22+
++count;
23+
}
24+
if (count == ones) {
25+
++left;
26+
} else if (count == 2 * ones) {
27+
++right;
28+
}
29+
}
30+
return static_cast<int64_t>(left) * right % MOD;
31+
}
32+
};

0 commit comments

Comments
 (0)