
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find number of good ways to split a string using Python
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
- Related Articles
- Program to find number of ways to split a string in Python
- Program to find number of ways we can split a palindrome in python
- Program to find number of ways to split array into three subarrays in Python
- Program to find number of good leaf nodes pairs using Python
- Program to find number of ways to form a target string given a dictionary in Python
- Program to find split a string into the max number of unique substrings in Python
- Program to find a good string from a given string in Python
- Program to find number of good pairs in Python
- Program to find number of good triplets in Python
- Program to find number of different integers in a string using Python
- Python program to split and join a string?
- Java Program to split a string using Regular Expression
- Python Program to Split a String by Custom Lengths
- Program to find number of ways we can decode a message in Python
- Program to find number of ways we can reach to the next floor using stairs in Python
