Given a binary string s, you can split s into 3 non-empty strings
s1, s2, and s3 where s1 + s2 + s3 = s.
Return the number of ways s can be split such that the number of ones is the same in s1, s2, and s3. Since the answer may be too large, return it
modulo10^9 + 7.
Input: s ="10101"Output: 4Explanation: There are four ways to split s in3 parts where each part contain the same number of letters '1'."1|010|1""1|01|01""10|10|1""10|1|01"
If the total number of ‘1’s in the string is not divisible by 3, it’s impossible to split as required. If there are no ‘1’s, any two split points will work. Otherwise, we count the number of ways to choose the split points so that each part contains exactly one-third of the total ‘1’s.
classSolution {
public:int numWays(string s) {
int n = s.size(), mod =1e9+7;
int ones =0;
for (char c : s) if (c =='1') ones++;
if (ones ==0) return (longlong)(n -1) * (n -2) /2% mod;
if (ones %3!=0) return0;
int k = ones /3, cnt1 =0, cnt2 =0, t =0;
for (char c : s) {
if (c =='1') t++;
if (t == k) cnt1++;
elseif (t ==2* k) cnt2++;
}
return (longlong)cnt1 * cnt2 % mod;
}
};
classSolution {
publicintnumWays(String s) {
int n = s.length(), mod = 1_000_000_007;
int ones = 0;
for (char c : s.toCharArray()) if (c =='1') ones++;
if (ones == 0) return (int)((long)(n-1)*(n-2)/2 % mod);
if (ones % 3 != 0) return 0;
int k = ones / 3, cnt1 = 0, cnt2 = 0, t = 0;
for (char c : s.toCharArray()) {
if (c =='1') t++;
if (t == k) cnt1++;
elseif (t == 2*k) cnt2++;
}
return (int)((long)cnt1 * cnt2 % mod);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funnumWays(s: String): Int {
val n = s.length
val mod = 1_000_000_007
val ones = s.count { it=='1' }
if (ones ==0) return ((n-1).toLong()*(n-2)/2 % mod).toInt()
if (ones % 3!=0) return0val k = ones / 3var cnt1 = 0; var cnt2 = 0; var t = 0for (c in s) {
if (c =='1') t++if (t == k) cnt1++elseif (t ==2*k) cnt2++ }
return ((cnt1.toLong() * cnt2) % mod).toInt()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defnumWays(self, s: str) -> int:
n, mod = len(s), 10**9+7 ones = s.count('1')
if ones ==0:
return (n-1)*(n-2)//2% mod
if ones %3!=0:
return0 k = ones //3 cnt1 = cnt2 = t =0for c in s:
if c =='1':
t +=1if t == k:
cnt1 +=1elif t ==2*k:
cnt2 +=1return cnt1 * cnt2 % mod
impl Solution {
pubfnnum_ways(s: String) -> i32 {
let n = s.len();
let modv =1_000_000_007;
let ones = s.chars().filter(|&c| c =='1').count();
if ones ==0 {
return ((n-1)*(n-2)/2% modv) asi32;
}
if ones %3!=0 {
return0;
}
let k = ones /3;
let (mut cnt1, mut cnt2, mut t) = (0, 0, 0);
for c in s.chars() {
if c =='1' { t +=1; }
if t == k { cnt1 +=1; }
elseif t ==2*k { cnt2 +=1; }
}
((cnt1 asi64* cnt2 asi64) % modv) asi32 }
}