Program to find split a string into the max number of unique substrings in Python

PythonServer Side ProgrammingProgramming

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
raja
Updated on 04-Oct-2021 10:07:49

Advertisements