Count substrings with same first and last characters | Most efficient C # program to count all substrings with same first and last characters . ; assuming lower case only ; Calculating frequency of each character in the string . ; Computing result using counts ; Driver code
using System ; class GFG { static readonly int MAX_CHAR = 26 ; static int countSubstringWithEqualEnds ( String s ) { int result = 0 ; int n = s . Length ; int [ ] count = new int [ MAX_CHAR ] ; for ( int i = 0 ; i < n ; i ++ ) count [ s [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) result += ( count [ i ] * ( count [ i ] + 1 ) / 2 ) ; return result ; } public static void Main ( ) { String s = " abcab " ; Console . Write ( countSubstringWithEqualEnds ( s ) ) ; } }