Sum of all distances between occurrences of same characters in a given string | C ++ program for the above approach ; Function to calculate the sum of distances between occurrences of same characters in a string ; If similar characters are found ; Add the difference of their positions ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( string s ) { int sum = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { for ( int j = i + 1 ; j < s . size ( ) ; j ++ ) { if ( s [ i ] == s [ j ] ) { sum += ( j - i ) ; } } } return sum ; } int main ( ) { string s = " ttt " ; cout << findSum ( s ) << endl ; }