Sum of all distances between occurrences of same characters in a given string | Java 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
import java . util . * ; class GFG { static int findSum ( String s ) { int sum = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { for ( int j = i + 1 ; j < s . length ( ) ; j ++ ) { if ( s . charAt ( i ) == s . charAt ( j ) ) { sum += ( j - i ) ; } } } return sum ; } public static void main ( String [ ] args ) { String s = " ttt " ; System . out . print ( findSum ( s ) + "NEW_LINE"); } }