1573. Number of Ways to Split a String
Given a binary string s (a string consisting only of ‘0’s and ‘1’s), we can split s into 3 non-empty strings s1, s2, s3 (s1+ s2+ s3 = s).
Return the number of ways s can be split such that the number of characters ‘1’ is the same in s1, s2, and s3.
Since the answer may be too large, return it modulo 10^9 + 7.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { private: const int MOD = 1e9 + 7; public: int numWays(string s) { int len = s.length(); vector<int> places; for(int i = 0; i < len; i++) { if (s[i] == '1') { places.push_back(i); } }
return places.size() % 3 != 0 || len < 3 ? 0 : places.empty() ? ((long)(len - 2) * (long)(len - 1) / 2) % MOD : ((long)(places[(int)places.size() / 3] - places[(int)places.size() / 3 - 1]) * (long)(places[(int)places.size() / 3 * 2] - places[(int)places.size() / 3 * 2 - 1])) % MOD; } };
|