Given a string str, the task is to split the string into maximum number of unique substrings possible and print their count.
Examples:
Input: str = “ababccc”
Output: 5
Explanation:
Split the given string into the substrings “a”, “b”, “ab”, “c” and “cc”.
Therefore, the maximum count of unqiue substrings is 5Input: 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 and update 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:
Java
// Java program for the above approach import 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 Code class GFG { public static void main(String[] args) { Solution st = new Solution(); String S = "ababccc"; int res = st.maxUniqueSplit(S); System.out.println(res); } } |
5
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

