Suppose we have a string s. Now a split is said to be a good split when we can split s into 2 non-empty strings p and q where its concatenation is equal to s and the number of distinct letters in p and q are the equal. We have to find the number of good splits we can make in s.
So, if the input is like s = "xxzxyx", then the output will be 2 as there are multiple ways of splitting but if we split like ("xxz", "xyx") or ("xxzx", "yx") then they are good.
To solve this, we will follow these steps −
result := 0
left := an empty mal to count frequency of items
right := Count each character's frequency present in s
for each c in s, do
left[c] := left[c] + 1
right[c] := right[c] - 1
if right[c] is zero, then
remove right[c]
if size of left is same as size of right, then
result := result + 1
return result
Let us see the following implementation to get better understanding −
Example
from collections import Counter def solve(s): result = 0 left, right = Counter(), Counter(s) for c in s: left[c] += 1 right[c] -= 1 if not right[c]: del right[c] if len(left) == len(right): result += 1 return result s = "xxzxyx" print(solve(s))
Input
"xxzxyx"
Output
2