Count substrings with same first and last characters | assuming lower case only ; Calculating frequency of each character in the string . ; Computing result using counts ; Driver Code
< ? php $ MAX_CHAR = 26 ; function countSubstringWithEqualEnds ( $ s ) { global $ MAX_CHAR ; $ result = 0 ; $ n = strlen ( $ s ) ; $ count = array_fill ( 0 , $ MAX_CHAR , 0 ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ count [ ord ( $ s [ $ i ] ) - ord ( ' a ' ) ] ++ ; for ( $ i = 0 ; $ i < $ MAX_CHAR ; $ i ++ ) $ result += ( $ count [ $ i ] * ( $ count [ $ i ] + 1 ) / 2 ) ; return $ result ; } $ s = " abcab " ; echo countSubstringWithEqualEnds ( $ s ) ; ? >