Count of sub | C ++ implementation of the approach ; Function to return the count of valid sub - strings ; Variable ans to store all the possible substrings Initialize its value as total number of substrings that can be formed from the given string ; Stores recent index of the characters ; If character is a update a 's index  and the variable ans ; If character is b update b 's index  and the variable ans ; If character is c update c 's index  and the variable ans ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CountSubstring ( char str [ ] , int n ) { int ans = ( n * ( n + 1 ) ) / 2 ; int a_index = 0 ; int b_index = 0 ; int c_index = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' a ' ) { a_index = i + 1 ; ans -= min ( b_index , c_index ) ; } else if ( str [ i ] == ' b ' ) { b_index = i + 1 ; ans -= min ( a_index , c_index ) ; } else { c_index = i + 1 ; ans -= min ( a_index , b_index ) ; } } return ans ; } int main ( ) { char str [ ] = " babac " ; int n = strlen ( str ) ; cout << CountSubstring ( str , n ) ; return 0 ; }