Number of sub | Java implementation of the approach ; Function to return the count of required sub - strings ; Left and right counters for characters on both sides of sub - string window ; Left and right pointer on both sides of sub - string window ; Initialize the frequency ; Result and length of string ; Initialize the left pointer ; Initialize the right pointer ; Traverse all the window sub - strings ; Counting the characters on left side of the sub - string window ; Counting the characters on right side of the sub - string window ; Add the possible sub - strings on both sides to result ; Setting the frequency for next sub - string window ; Reset the left and right counters ; Driver code
class GFG { static int countSubString ( char [ ] 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 [ left ] != c && left < len ) { left ++ ; leftCount ++ ; } right = left + 1 ; while ( freq != ( k - 1 ) && ( right - 1 ) < len ) { if ( s [ right ] == c ) freq ++ ; right ++ ; } while ( left < len && ( right - 1 ) < len ) { while ( s [ left ] != c && left < len ) { left ++ ; leftCount ++ ; } while ( right < len && s [ right ] != c ) { if ( s [ 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 = " abada " ; char c = ' a ' ; int k = 2 ; System . out . println ( countSubString ( s . toCharArray ( ) , c , k ) ) ; } }