Number of sub | 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
< ? php function countSubString ( $ s , $ c , $ k ) { $ leftCount = 0 ; $ rightCount = 0 ; $ left = 0 ; $ right = 0 ; $ freq = 0 ; $ result = 0 ; $ len = strlen ( $ s ) ; 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 ; } $ s = " abada " ; $ c = ' a ' ; $ k = 2 ; echo countSubString ( $ s , $ c , $ k ) , " STRNEWLINE " ; ? >