Length of the smallest sub | C ++ program to find the length of the smallest substring consisting of maximum distinct characters ; Find maximum distinct characters in any string ; Initialize all character 's count with 0 ; Increase the count in array if a character is found ; size of given string ; Find maximum distinct characters in any string ; result ; Brute force approach to find all substrings ; We have to check here both conditions together 1. substring ' s ▁ distinct ▁ characters ▁ is ▁ equal ▁ ▁ to ▁ maximum ▁ distinct ▁ characters ▁ ▁ 2 . ▁ substring ' s length should be minimum ; Driver program to test above function ; Input String
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define NO_OF_CHARS  256 NEW_LINE int max_distinct_char ( string str , int n ) { int count [ NO_OF_CHARS ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) count [ str [ i ] ] ++ ; int max_distinct = 0 ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) if ( count [ i ] != 0 ) max_distinct ++ ; return max_distinct ; } int smallesteSubstr_maxDistictChar ( string str ) { int n = str . size ( ) ; int max_distinct = max_distinct_char ( str , n ) ; int minl = n ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { string subs = str . substr ( i , j ) ; int subs_lenght = subs . size ( ) ; int sub_distinct_char = max_distinct_char ( subs , subs_lenght ) ; if ( subs_lenght < minl && max_distinct == sub_distinct_char ) { minl = subs_lenght ; } } } return minl ; } int main ( ) { string str = " AABBBCBB " ; int len = smallesteSubstr_maxDistictChar ( str ) ; cout << " ▁ The ▁ length ▁ of ▁ the ▁ smallest ▁ substring " " ▁ consisting ▁ of ▁ maximum ▁ distinct ▁ " " characters ▁ : ▁ " << len ; return 0 ; }