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 final result ; Traversal of string ; Store answer for every iteration ; Map traversal ; Compare current char ; Print the final count ; Driver Code ; Given string ; Length of the string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstring ( string s , int n ) { map < char , int > m ; for ( int i = 0 ; i < n ; i ++ ) m [ s [ i ] ] ++ ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int cnt = 0 ; m [ s [ i ] ] -- ; for ( auto value : m ) { if ( value . first == s [ i ] ) { continue ; } else { cnt += value . second ; } } ans += cnt ; } cout << ans ; } int main ( ) { string S = " abcab " ; int N = 5 ; countSubstring ( S , N ) ; return 0 ; }