Count of substrings which contains a given character 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
function countSubString ( s , c , k ) { var leftCount = 0 , rightCount = 0 ; var left = 0 , right = 0 ; var freq = 0 ; var 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 ; } var s = " " ; var c = " " ; var k = 2 ; document . write ( countSubString ( s , c , k ) ) ;