LeetCode 1573: Number of Ways to Split a String
LeetCode 1573 Solution Explanation
Explanation:
To solve this problem, we can iterate through the binary string s
and keep track of the total number of ones in the string. Then, we can find all possible ways to split the string into 3 parts such that each part contains the same number of ones. We can achieve this by counting the number of zeros between each pair of ones and calculate the total number of valid splits.
- Iterate through the string
s
and count the total number of ones. - If the total number of ones is not divisible by 3, return 0 as it is not possible to split the string into 3 parts with the same number of ones.
- Calculate the required number of ones in each part (
targetOnes
) by dividing the total number of ones by 3. - Initialize variables to keep track of the number of zeros between each pair of ones and the total number of ways to split the string.
- Iterate through the string
s
again and count the number of zeros between each pair of ones. Increment the count of zeros and if the count reaches thetargetOnes
, reset the count and increment the total number of ways. - Return the total number of ways modulo 10^9 + 7.
Time Complexity: O(n) where n is the length of the input string s
.
Space Complexity: O(1)
:
LeetCode 1573 Solutions in Java, C++, Python
class Solution {
public int numWays(String s) {
int ones = 0;
for (char c : s.toCharArray()) {
if (c == '1') ones++;
}
if (ones % 3 != 0) return 0;
int targetOnes = ones / 3;
if (targetOnes == 0) {
long ways = (long)(s.length() - 1) * (s.length() - 2) / 2;
return (int)(ways % (1e9 + 7));
}
int countZeros = 0;
long totalWays = 0;
for (char c : s.toCharArray()) {
if (c == '0') {
countZeros++;
} else {
if (countZeros == targetOnes) {
totalWays++;
countZeros = 0;
}
}
}
return (int)(totalWays % (1e9 + 7));
}
}
Interactive Code Editor for LeetCode 1573
Improve Your LeetCode 1573 Solution
Use the editor below to refine the provided solution for LeetCode 1573. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...