![]() |
VOOZH | about |
Given binary string s . find the maximum number of substrings it can be splitted into such that all substrings have equal number of 0s and 1s. If it is not possible to split s satisfying the conditions then return -1.
Examples:
Input: s = "0100110101"
Output: 4
Explanation: The required substrings are "01", "0011", "01" and "01".
Input: s = "0111100010"
Output: 3
Explanation: The required substrings are"01","111000"and"10".
The idea is to use a stack to simulate cancellation of opposite characters (0 and 1), similar to balanced parentheses.
4
Time Complexity: O(n)
Space Complexity: O(n)
The idea is to traverse the string while counting
0s and1s. Whenever both counts become equal, a balanced substring is found, so we increment the count. After traversal, if the total number of0s and1s are not equal, we return-1; otherwise, we return the count.
4
Time Complexity: O(n)
Space Complexity: O(1)