Count substrings with different first and last characters | C # program for the above approach ; 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 readonly result ; Traversal of String ; Store answer for every iteration ; Map traversal ; Compare current char ; Print the readonly count ; Driver Code ; Given String ; Length of the String ; Function call
using System ; using System . Collections . Generic ; class GFG { static void countSubString ( char [ ] s , int n ) { Dictionary < char , int > mp = new Dictionary < char , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( mp . ContainsKey ( s [ i ] ) ) { mp [ s [ i ] ] = mp [ s [ i ] ] + 1 ; } else { mp . Add ( s [ i ] , 1 ) ; } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int cnt = 0 ; if ( mp . ContainsKey ( s [ i ] ) ) { mp [ s [ i ] ] = mp [ s [ i ] ] - 1 ; foreach ( KeyValuePair < char , int > value in mp ) { if ( value . Key == s [ i ] ) { continue ; } else { cnt += value . Value ; } } ans += cnt ; } } Console . Write ( ans ) ; } public static void Main ( String [ ] args ) { String S = " abcab " ; int N = 5 ; countSubString ( S . ToCharArray ( ) , N ) ; } }