
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
- Related Questions & Answers
- Program to count number of distinct characters of every substring of a string in Python
- Python program to count number of substring present in string
- Find total number of distinct years from a string in C++
- Count the number of distinct values in MySQL?
- Count number of substrings with exactly k distinct characters in C++
- Find total number of distinct years from a string in C++ Program
- Number of Distinct Islands in C++
- Maximum Number of Occurrences of a Substring in C++
- Count distinct points visited on the number line in C++
- C# program to count the number of words in a string
- Program to count number of unique subsequences of a string in C++
- Number of Distinct Islands II in C++
- Program to count number of distinct substrings in s in Python
- Count number of distinct pairs whose sum exists in the given array in C++
- Absolute distinct count in a sorted array in C++?