text: Count of substrings from given Ternary strings containing characters at least once | C ++ program for above approach ; Function to count the number of substrings consists of 0 , 1 , and 2 ; Initialize frequency array of size 3 ; Stores the resultant count ; Traversing string str ; Update frequency array ; If all the characters are present counting number of substrings possible ; Update number of substrings ; Return the number of substrings ; Driver Code
code: #include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; int countSubstrings ( string & str ) { int freq [ 3 ] = { 0 } ; int count = 0 ; int i = 0 ; for ( int j = 0 ; j < str . length ( ) ; j ++ ) { freq [ str [ j ] - '0' ] ++ ; while ( freq [ 0 ] > 0 && freq [ 1 ] > 0 && freq [ 2 ] > 0 ) { freq [ str [ i ++ ] - '0' ] -- ; } count += i ; } return count ; } int main ( ) { string str = "00021" ; int count = countSubstrings ( str ) ; cout << count ; return 0 ; }