Count of sub | 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
< ? php function CountSubstring ( $ str , $ n ) { $ ans = ( $ n * ( $ n + 1 ) ) / 2 ; $ a_index = 0 ; $ b_index = 0 ; $ c_index = 0 ; for ( $ 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 ; } { $ str = str_split ( " babac " ) ; $ n = sizeof ( $ str ) ; echo ( CountSubstring ( $ str , $ n ) ) ; }