Sub | Java implementation of above approach ; Function that counts all the sub - strings of length ' k ' which have all identical characters ; count of sub - strings , length , initial position of sliding window ; map to store the frequency of the characters of sub - string ; increase the frequency of the character and length of the sub - string ; if the length of the sub - string is greater than K ; remove the character from the beginning of sub - string ; if the length of the sub string is equal to k and frequency of one of its characters is equal to the length of the sub - string i . e . all the characters are same increase the count ; display the number of valid sub - strings ; Driver code
import java . util . * ; class GFG { static void solve ( String s , int k ) { int count = 0 , length = 0 , pos = 0 ; HashMap < Character , Integer > m = new HashMap < Character , Integer > ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( m . containsKey ( s . charAt ( i ) ) ) m . put ( s . charAt ( i ) , m . get ( s . charAt ( i ) ) + 1 ) ; else m . put ( s . charAt ( i ) , 1 ) ; length ++ ; if ( length > k ) { m . put ( s . charAt ( pos ) , m . get ( s . charAt ( pos ) ) - 1 ) ; pos ++ ; length -- ; } if ( length == k && m . get ( s . charAt ( i ) ) == length ) count ++ ; } System . out . println ( count ) ; } public static void main ( String [ ] args ) { String s = " aaaabbbccdddd " ; int k = 4 ; solve ( s , k ) ; } }