Count of sub | C ++ implementation of the approach ; Function to return the number of sub - strings that do not contain the given character c ; Length of the string ; Traverse in the string ; If current character is different from the given character ; Update the number of sub - strings ; Reset count to 0 ; For the characters appearing after the last occurrence of c ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstrings ( string s , char c ) { int n = s . length ( ) ; int cnt = 0 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] != c ) cnt ++ ; else { sum += ( cnt * ( cnt + 1 ) ) / 2 ; cnt = 0 ; } } sum += ( cnt * ( cnt + 1 ) ) / 2 ; return sum ; } int main ( ) { string s = " baa " ; char c = ' b ' ; cout << countSubstrings ( s , c ) ; return 0 ; }