Count substrings with different first and last characters | Function to count the substrings having different first & last character ; Stores frequency of each char ; Loop to store frequency of the characters in a Map ; To store final result ; Traversal of string ; Store answer for every iteration ; Map traversal ; Compare current char ; Print the final count ; Given string ; Length of the string ; Function Call
def countSubstring ( s , n ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if s [ i ] in m : NEW_LINE INDENT m [ s [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ s [ i ] ] = 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE if s [ i ] in m : NEW_LINE INDENT m [ s [ i ] ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ s [ i ] ] = - 1 NEW_LINE DEDENT for value in m : NEW_LINE INDENT if ( value == s [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT cnt += m [ value ] NEW_LINE DEDENT DEDENT ans += cnt NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT S = " abcab " NEW_LINE N = 5 NEW_LINE countSubstring ( S , N ) NEW_LINE