Number of Ways to Split a String LeetCode solution in Java

1
class Solution {
2
public int numWays(String s) {
3
long n = s.length();
4
long one = 0; // to count number of ones
5
long mod = 1_000_000_007;
6
char[] c = s.toCharArray();
7
for (int i = 0; i < c.length; i++) {
8
if (c[i] == '1') one++;
9
}
10

11
// there will be 3 cases
12
// 1.no ones present in the string
13
// 2.number of ones present in the string isnt divisible by 3(since we need to cut 3 parts)
14
// 3.number of ones divisible by 3
15

16
if (one == 0) // case 1
17
{
18
return (int) ((((n - 1) * (n - 2)) / 2) % mod);
19
}
20
if (one % 3 != 0) // case 2,which means we cant split ones equally
21
return 0;
22
// case 3
23
long ones = one / 3; // number of ones that should be present in each part
24
one = 0;
25
long part1 = 0; // number of ways in which part1 and part2 can be split
26
long part2 = 0;
27
for (int i = 0; i < c.length; i++) {
28
if (c[i] == '1') one++;
29
if (one == ones) part1++;
30
if (one == 2 * ones) part2++;
31
}
32

33
return (int) ((part1 * part2) % mod);
34
}
35
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0