Count substrings with different first and last characters | Java 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
import java . util . * ; class GFG { static void countSubString ( char [ ] s , int n ) { HashMap < Character , Integer > mp = new HashMap < Character , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( mp . containsKey ( s [ i ] ) ) { mp . put ( s [ i ] , mp . get ( s [ i ] ) + 1 ) ; } else { mp . put ( s [ i ] , 1 ) ; } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int cnt = 0 ; if ( mp . containsKey ( s [ i ] ) ) { mp . put ( s [ i ] , mp . get ( s [ i ] ) - 1 ) ; for ( Map . Entry < Character , Integer > value : mp . entrySet ( ) ) { if ( value . getKey ( ) == s [ i ] ) { continue ; } else { cnt += value . getValue ( ) ; } } ans += cnt ; } } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { String S = " abcab " ; int N = 5 ; countSubString ( S . toCharArray ( ) , N ) ; } }