Count of substrings which contains a given character K times | Java program to count the number of substrings which contains the character C exactly K times ; Function to count the number of substrings which contains the character C exactly K times ; left and right counters for characters on both sides of substring window ; left and right pointer on both sides of substring window ; initialize the frequency ; result and length of string ; initialize the left pointer ; initialize the right pointer ; traverse all the window substrings ; counting the characters on leftSide of substring window ; counting the characters on rightSide of substring window ; Add the possible substrings on both sides to result ; Setting the frequency for next substring window ; reset the left , right counters ; Driver code
class GFG { static int countSubString ( String s , char c , int k ) { int leftCount = 0 , rightCount = 0 ; int left = 0 , right = 0 ; int freq = 0 ; int result = 0 , len = s . length ( ) ; while ( s . charAt ( left ) != c && left < len ) { left ++ ; leftCount ++ ; } right = left + 1 ; while ( freq != ( k - 1 ) && ( right - 1 ) < len ) { if ( s . charAt ( right ) == c ) { freq ++ ; } right ++ ; } while ( left < len && ( right - 1 ) < len ) { while ( s . charAt ( left ) != c && left < len ) { left ++ ; leftCount ++ ; } while ( right < len && s . charAt ( right ) != c ) { if ( s . charAt ( right ) == c ) { freq ++ ; } right ++ ; rightCount ++ ; } result = result + ( leftCount + 1 ) * ( rightCount + 1 ) ; freq = k - 1 ; leftCount = 0 ; rightCount = 0 ; left ++ ; right ++ ; } return result ; } public static void main ( String args [ ] ) { String s = "3123231" ; char c = '3' ; int k = 2 ; System . out . println ( countSubString ( s , c , k ) ) ; } }