Count substrings with same first and last characters | Space efficient Python3 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
def countSubstringWithEqualEnds ( s ) : NEW_LINE INDENT result = 0 ; NEW_LINE n = len ( s ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT if ( s [ i ] == s [ j ] ) : NEW_LINE INDENT result = result + 1 NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT s = " abcab " ; NEW_LINE print ( countSubstringWithEqualEnds ( s ) ) NEW_LINE