Count substrings with same first and last characters | Space efficient C ++ program to count all substrings with same first and last characters . ; Iterating through all substrings in way so that we can find first and last character easily ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstringWithEqualEnds ( string s ) { int result = 0 ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i ; j < n ; j ++ ) if ( s [ i ] == s [ j ] ) result ++ ; return result ; } int main ( ) { string s ( " abcab " ) ; cout << countSubstringWithEqualEnds ( s ) ; return 0 ; }