Number of Ways to Split a String LeetCode solution in Python

1
class Solution:
2
def numWays(self, s: str) -> int:
3
ones = 0
4

5
# Count number of Ones
6
for char in s:
7
if char == "1":
8
ones += 1
9

10
# Can't be grouped equally if the ones are not divisible by 3
11
if ones > 0 and ones % 3 != 0:
12
return 0
13

14
# Ways of selecting two dividers from n - 1 dividers
15
if ones == 0:
16
n = len(s)
17
# n = {3: 1, 4: 3, 5: 6, 6: 10, 7: 15 ... }
18
return (((n - 1) * (n - 2)) // 2) % ((10**9) + 7)
19

20
# Number of ones in each group
21
ones_interval = ones // 3
22

23
# Number of zeroes which lie on the borders
24
left, right = 0, 0
25

26
# Iterator
27
i = 0
28
temp = 0
29

30
# Finding the zeroes on the left and right border
31
while i < len(s):
32
temp += int(s[i]) & 1
33
if temp == ones_interval:
34
if s[i] == "0":
35
left += 1
36
if temp == 2 * ones_interval:
37
if s[i] == "0":
38
right += 1
39
i += 1
40

41
# The result is the product of number of (left + 1) and (right + 1)
42
# Because let's assume it as we only want to fill up the middle group
43
# The solution would be if we have zero then there might be a zero in the middle
44
# Or there might not be the zero, so this might case is added and then
45
# the events are independent so product of both the events
46
return ((left + 1) * (right + 1)) % ((10**9) + 7)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0