- 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 split a string into the max number of unique substrings in Python

Suppose we have a string s, we have to find the maximum number of unique substrings that the given string can be split into. We can split string s into any list of non-empty substrings such that the concatenation of the substrings forms the original string. But we must split the substrings such that all of them are same.

So, if the input is like s = "pqpqrrr", then the output will be 5 because we can split it like ['p', 'q', 'pq', 'r', 'rr']. If we split like ['p', 'q', 'p', 'q', 'r', 'rr'] is not valid because here 'p' and 'q' are present multiple times.

To solve this, we will follow these steps −

- res := a list with only one element 0
- Define a function dfs() . This will take s, path which is a new empty set
- if s is empty, then
- res[0] := maximum of res[0] and size of path
- return

- for i in range 1 to size of s, do
- x := subarray of s[from index 0 to i-1]
- if x not in the path, then
- dfs(substring of s[from index i to end], path U {x})

- From the main method do the following −
- dfs(s)
- return res[0]

## Example

Let us see the following implementation to get better understanding −

def solve(s): res = [0] def dfs(s, path=set()): if not s: res[0] = max(res[0], len(path)) return for i in range(1, len(s)+1): x = s[:i] if x not in path: dfs(s[i:], path|{x}) dfs(s) return res[0] s = "pqpqrrr" print(solve(s))

## Input

"pqpqrrr"

## Output

5

- Related Articles
- Program to find number of ways to split a string in Python
- Program to find out number of distinct substrings in a given string in python
- Program to find number of different substrings of a string for different queries in Python
- Program to find number of good ways to split a string using Python
- Program to find total sum of all substrings of a number given as string in Python
- How to split a long string into a vector of substrings of equal sizes in R?
- Program to find number of ways to split array into three subarrays in Python
- Python program to split string into k distinct partitions
- Golang program to splitting into number of substrings
- Program to find total similarities of a string and its substrings in Python
- Program to find out the number of pairs of equal substrings in Python
- Program to find maximum number of non-overlapping substrings in Python
- Find the Number of Substrings of a String using C++
- Java Program to split into a number of sub-strings
- C# Program to find all substrings in a string

Advertisements