Count of all unique substrings with non-repeating characters

10 Mar, 2022
Given a string str consisting of lowercase characters, the task is to find the total numbers of unique substrings with non-repeating characters.Examples:  
Input: str = “abba” Output: 4 Explanation: There are 4 unique substrings. They are: “a”, “ab”, “b”, “ba”.Input: str = “acbacbacaa” Output: 10  
 
Approach: The idea is to iterate over all the substrings. For every substring, check whether each particular character has previously occurred or not. If so, then increase the count of required substrings. In the end return this count as count of all unique substrings with non-repeating characters.Below is the implementation of the above approach:  
CPP
Java
Python3
C#
Javascript
// C++ program to find the count of// all unique sub-strings with// non-repeating characters #include <bits/stdc++.h>using namespace std; // Function to count all unique// distinct character substringsint distinctSubstring(string& P, int N){    // Hashmap to store all substrings    unordered_set<string> S;     // Iterate over all the substrings    for (int i = 0; i < N; ++i) {         // Boolean array to maintain all        // characters encountered so far        vector<bool> freq(26, false);         // Variable to maintain the        // substring till current position        string s;         for (int j = i; j < N; ++j) {             // Get the position of the            // character in the string            int pos = P[j] - 'a';             // Check if the character is            // encountred            if (freq[pos] == true)                break;             freq[pos] = true;             // Add the current character            // to the substring            s += P[j];             // Insert substring in Hashmap            S.insert(s);        }    }     return S.size();} // Driver codeint main(){    string S = "abba";    int N = S.length();     cout << distinctSubstring(S, N);     return 0;}
// Java program to find the count of// all unique sub-Strings with// non-repeating charactersimport java.util.*; class GFG{  // Function to count all unique// distinct character subStringsstatic int distinctSubString(String P, int N){    // Hashmap to store all subStrings    HashSet<String> S = new HashSet<String>();      // Iterate over all the subStrings    for (int i = 0; i < N; ++i) {          // Boolean array to maintain all        // characters encountered so far        boolean []freq = new boolean[26];          // Variable to maintain the        // subString till current position        String s = "";          for (int j = i; j < N; ++j) {              // Get the position of the            // character in the String            int pos = P.charAt(j) - 'a';              // Check if the character is            // encountred            if (freq[pos] == true)                break;              freq[pos] = true;              // Add the current character            // to the subString            s += P.charAt(j);              // Insert subString in Hashmap            S.add(s);        }    }      return S.size();}  // Driver codepublic static void main(String[] args){    String S = "abba";    int N = S.length();      System.out.print(distinctSubString(S, N));}} // This code is contributed by Rajput-Ji
# Python3 program to find the count of# all unique sub-strings with# non-repeating characters # Function to count all unique# distinct character substringsdef distinctSubstring(P, N):         # Hashmap to store all substrings    S = dict()     # Iterate over all the substrings    for i in range(N):         # Boolean array to maintain all        # characters encountered so far        freq = [False]*26         # Variable to maintain the        # substring till current position        s = ""         for j in range(i,N):             # Get the position of the            # character in the string            pos = ord(P[j]) - ord('a')             # Check if the character is            # encountred            if (freq[pos] == True):                break             freq[pos] = True             # Add the current character            # to the substring            s += P[j]             # Insert substring in Hashmap            S[s] = 1     return len(S) # Driver codeS = "abba"N = len(S) print(distinctSubstring(S, N)) # This code is contributed by mohit kumar 29   
// C# program to find the count of// all unique sub-Strings with// non-repeating charactersusing System;using System.Collections.Generic; class GFG{   // Function to count all unique// distinct character subStringsstatic int distinctSubString(String P, int N){    // Hashmap to store all subStrings    HashSet<String> S = new HashSet<String>();       // Iterate over all the subStrings    for (int i = 0; i < N; ++i) {           // Boolean array to maintain all        // characters encountered so far        bool []freq = new bool[26];           // Variable to maintain the        // subString till current position        String s = "";           for (int j = i; j < N; ++j) {               // Get the position of the            // character in the String            int pos = P[j] - 'a';               // Check if the character is            // encountred            if (freq[pos] == true)                break;               freq[pos] = true;               // Add the current character            // to the subString            s += P[j];               // Insert subString in Hashmap            S.Add(s);        }    }     return S.Count;}   // Driver codepublic static void Main(String[] args){    String S = "abba";    int N = S.Length;       Console.Write(distinctSubString(S, N));}} // This code is contributed by Rajput-Ji
<script> // JavaScript program to find the count of// all unique sub-strings with// non-repeating characters  // Function to count all unique// distinct character substringsfunction distinctSubstring(P, N){    // Hashmap to store all substrings    var S = new Set();     // Iterate over all the substrings    for (var i = 0; i < N; ++i) {         // Boolean array to maintain all        // characters encountered so far        var freq = Array(26).fill(false);         // Variable to maintain the        // substring till current position        var s = "";         for (var j = i; j < N; ++j) {             // Get the position of the            // character in the string            var pos = P[j].charCodeAt(0) - 'a'.charCodeAt(0);             // Check if the character is            // encountred            if (freq[pos] == true)                break;             freq[pos] = true;             // Add the current character            // to the substring            s += P[j];             // Insert substring in Hashmap            S.add(s);        }    }     return S.size;} // Driver codevar S = "abba";var N = S.length;document.write( distinctSubstring(S, N));  </script>
4
 
Time Complexity: O(N2) where N is the length of the string. 
mohit kumar 29
Rajput-Ji
itsok
surinderdawra388
simmytarika5
substring
Greedy
Pattern Searching
Strings
Strings
Greedy
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Policemen catch thieves
K Centers Problem | Set 1 (Greedy Approximate Algorithm)
Maximize difference between the Sum of the two halves of the Array after removal of N elements
Minimize Cash Flow among a given set of friends who have borrowed money from each other
Minimum time taken by each job to be completed given by a Directed Acyclic Graph
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Check if an URL is valid or not using Regular Expression
Check if a string is substring of another
Boyer Moore Algorithm for Pattern Searching