Split a string into maximum number of unique substrings

18 Jul, 2021
Given string str, the task is to split the string into the maximum number of unique substrings possible and print their count.
Examples: 
Input: str = “ababccc”Output: 5Explanation:Split the given string into the substrings “a”, “b”, “ab”, “c” and “cc”.Therefore, the maximum count of unique substrings is 5.
Input: str = “aba”Output: 2
Approach: The problem can be solved by the Greedy approach. Follow the steps below to solve the problem: 
Initialize a Set S.Iterate over the characters of the string str and for each i and find the substring up to that index.If the given substring is not present in the Set S, insert it updates the maximum count, and remove it from the Set, because the same character cannot be reused.Return the maximum count.
Initialize a Set S.
Iterate over the characters of the string str and for each i and find the substring up to that index.
If the given substring is not present in the Set S, insert it updates the maximum count, and remove it from the Set, because the same character cannot be reused.
Return the maximum count.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// CPP program for the above approach#include<bits/stdc++.h>using namespace std; // Utility function to find maximum count of// unique substrings by splitting the stringint maxUnique(string S, set<string> st){   // Stores maximum count of unique substring  // by splitting the string into substrings  int mx = 0;   // Iterate over the characters of the string  for (int i = 1; i <= S.length(); i++)  {     // Stores prefix substring    string tmp = S.substr(0, i);     // Check if the current substring    // already exists    if (st.find(tmp) == st.end())    {       // Insert tmp into set      st.insert(tmp);       // Recursively call for remaining      // characters of string      mx = max(mx, maxUnique(S.substr(i), st) + 1);       // Remove from the set      st.erase(tmp);    }  }   // Return answer  return mx;}  // Function to find the maximum count of// unique substrings by splitting a string// into maximum number of unique substringsint maxUniqueSplit(string S){  set<string> st;  return maxUnique(S, st);} // Driver Codeint main(){  string S = "ababccc";  int res = maxUniqueSplit(S);   cout<<res;} // This code is contributed by jana_sayantan.
// Java program for the above approachimport java.io.*;import java.util.*;class Solution {     // Function to find the maximum count of    // unique substrings by splitting a string    // into maximum number of unique substrings    public int maxUniqueSplit(String S)    {        return maxUnique(S, new HashSet<String>());    }     // Utility function to find maximum count of    // unique substrings by splitting the string    public int maxUnique(String S, Set<String> set)    {         // Stores maximum count of unique substring        // by splitting the string into substrings        int max = 0;         // Iterate over the characters of the string        for (int i = 1; i <= S.length(); i++) {             // Stores prefix substring            String tmp = S.substring(0, i);             // Check if the current substring            // already exists            if (!set.contains(tmp)) {                 // Insert tmp into set                set.add(tmp);                 // Recursively call for remaining                // characters of string                max = Math.max(max, maxUnique(                                        S.substring(i), set)                                        + 1);                 // Remove from the set                set.remove(tmp);            }        }         // Return answer        return max;    }} // Driver Codeclass GFG {     public static void main(String[] args)    {        Solution st = new Solution();        String S = "ababccc";        int res = st.maxUniqueSplit(S);         System.out.println(res);    }}
# Python3 program for the above approach # Utility function to find maximum count of# unique substrings by splitting the stringdef maxUnique(S):    global d     # Stores maximum count of unique substring    # by splitting the string into substrings    maxm = 0     # Iterate over the characters of the string    for i in range(1, len(S) + 1):         # Stores prefix substring        tmp = S[0:i]         # Check if the current substring        # already exists        if (tmp not in d):             # Insert tmp into set            d[tmp] = 1             # Recursively call for remaining            # characters of string            maxm = max(maxm, maxUnique(S[i:]) + 1)             # Remove from the set            del d[tmp]     # Return answer    return maxm # Driver Codeif __name__ == '__main__':       # Solution st = new Solution()    S = "ababccc"    d = {}    res = maxUnique(S)    # d = {}     print(res) # This code is contributed by mohit kumar 29.
// C# program for the above approachusing System;using System.Collections.Generic; class GFG {   // Function to find the maximum count of  // unique substrings by splitting a string  // into maximum number of unique substrings  public int maxUniqueSplit(String S)  {    return maxUnique(S, new HashSet<String>());  }   // Utility function to find maximum count of  // unique substrings by splitting the string  public int maxUnique(String S, HashSet<String> set)  {     // Stores maximum count of unique substring    // by splitting the string into substrings    int max = 0;     // Iterate over the characters of the string    for (int i = 1; i <= S.Length; i++) {       // Stores prefix substring      String tmp = S.Substring(0, i);       // Check if the current substring      // already exists      if (!set.Contains(tmp)) {         // Insert tmp into set        set.Add(tmp);         // Recursively call for remaining        // characters of string        max = Math.Max(max, maxUnique(          S.Substring(i), set)                       + 1);         // Remove from the set        set.Remove(tmp);      }    }     // Return answer    return max;  }} // Driver Codepublic class GFG {   public static void Main(String[] args)  {    Solution st = new Solution();    String S = "ababccc";    int res = st.maxUniqueSplit(S);     Console.WriteLine(res);  }} // This code contributed by shikhasingrajput
<script> // Javascript program for the above approach // Utility function to find maximum count of// unique substrings by splitting the stringfunction maxUnique(S, st){   // Stores maximum count of unique substring  // by splitting the string into substrings  var mx = 0;   // Iterate over the characters of the string  for (var i = 1; i <= S.length; i++)  {     // Stores prefix substring    var tmp = S.substring(0, i);     // Check if the current substring    // already exists    if (!st.has(tmp))    {       // Insert tmp into set      st.add(tmp);       // Recursively call for remaining      // characters of string      mx = Math.max(mx, maxUnique(S.substring(i), st) + 1);       // Remove from the set      st.delete(tmp);    }  }   // Return answer  return mx;}  // Function to find the maximum count of// unique substrings by splitting a string// into maximum number of unique substringsfunction maxUniqueSplit(S){  var st = new Set();  return maxUnique(S, st);} // Driver Codevar S = "ababccc";var res = maxUniqueSplit(S);document.write( res);  </script>
5
 
Time Complexity: O()
Auxiliary Space: O(N)
mohit kumar 29
bgangwar59
shikhasingrajput
importantly
jeetkaria
partition
substring
Backtracking
Strings
Strings
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
The Knight's tour problem | Backtracking-1
Backtracking | Introduction
m Coloring Problem | Backtracking-5
Hamiltonian Cycle | Backtracking-6
Backtracking to find all subsets
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
Different Methods to Reverse a String in C++