Count of substrings from given Ternary strings containing characters at least once | Java program for the 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
import java . util . * ; class GFG { public static int countSubstrings ( String str ) { int [ ] freq = new int [ 3 ] ; int count = 0 ; int i = 0 ; for ( int j = 0 ; j < str . length ( ) ; j ++ ) { freq [ str . charAt ( j ) - '0' ] ++ ; while ( freq [ 0 ] > 0 && freq [ 1 ] > 0 && freq [ 2 ] > 0 ) { freq [ str . charAt ( i ++ ) - '0' ] -- ; } count += i ; } return count ; } public static void main ( String [ ] args ) { String str = "00021" ; System . out . println ( countSubstrings ( str ) ) ; } }