Count number of Distinct Substring in a String in C++


According to the problem we are given a string str, we must count all the substrings in the given string. Substring is a string which is a part of an already existing string whose size may be smaller than or equal to the existing string.

Let's understand the problem and its solution with the help of examples.

Input − str = "wxyz";

Output − count of distinct substring is: 10

Explanation − Distinct substrings counted are −

wxyz, wxy, wx, w, xyz, xy, x, yz, y, z so their count is 10

Input − str = "zzzz"

Output − count of distinct substring is: 4

Explanation − Distinct substrings counted are −

zzzz, zzz, zz, z

Approach used in the below program as follows

  • Take a string str as an input.

  • Declare an empty unordered_set "myset".

  • Loop i from 0 move 1 step till i is less than the size of the string.

    • Declare a new string space "" (empty).

    • Loop j starting from i move 1 step at the time till j is less than the size of the string.

    • Concatenate the value of space on each step with str[j]

    • Insert space in myset.

  • Print the size of the str as an answer.

Example

 Live Demo

#include<iostream>
#include<unordered_set>
using namespace std;
int main(){
   string str = "aaaa";
   unordered_set<string> myset;
   int i, j;
   for (i = 0; i < str.size(); ++i){
      string space = "";
      for (j = i; j < str.size(); ++j){
         space = space + str[j];
         myset.insert(space);
       }
   }
   cout <<"count of distinct substring is: " <<str.size();
   return 0;
}

Output

If we run the above code we will get the following output −

count of distinct substring is: 4

Updated on: 14-Aug-2020

420 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements