- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 Questions & Answers
- 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 good ways to split a string using Python
- Program to find number of different substrings of a string for different queries in Python
- Find the Number of Substrings of a String using C++
- Program to find number of ways to split array into three subarrays in Python
- How to split a long string into a vector of substrings of equal sizes in R?
- Program to find total sum of all substrings of a number given as string in Python
- Program to find out the number of pairs of equal substrings in Python
- Python program to split string into k distinct partitions
- Java Program to split into a number of sub-strings
- Program to find maximum number of non-overlapping substrings in Python
- Program to find total similarities of a string and its substrings in Python
- Program to find number of substrings with only 1s using Python
- Program to find the number of unique integers in a sorted list in Python

Advertisements