Count substrings with same first and last characters | Space efficient PHP program to count all substrings with same first and last characters . ; Iterating through all substrings in way so that we can find first and last character easily ; Driver Code
< ? php function countSubstringWithEqualEnds ( $ s ) { $ result = 0 ; $ n = strlen ( $ s ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) for ( $ j = $ i ; $ j < $ n ; $ j ++ ) if ( $ s [ $ i ] == $ s [ $ j ] ) $ result ++ ; return $ result ; } $ s = " abcab " ; echo countSubstringWithEqualEnds ( $ s ) ;