Minimum distance between duplicates in a String | Java program for the above approach ; This function is used to find minimum distance between same repeating characters ; Store minimum distance between same repeating characters ; For loop to consider each element of string ; Comparison of string characters and updating the minDis value ; As this value would be least therefore break ; If minDis value is not updated that means no repeating characters ; Minimum distance is minDis - 1 ; Driver code ; Given input ; Function call
import java . io . * ; class GFG { static int shortestDistance ( String S , int N ) { int minDis = S . length ( ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { if ( S . charAt ( i ) == S . charAt ( j ) && ( j - i ) < minDis ) { minDis = j - i ; break ; } } } if ( minDis == S . length ( ) ) return - 1 ; else return minDis - 1 ; } public static void main ( String [ ] args ) { String S = " geeksforgeeks " ; int N = 13 ; System . out . println ( shortestDistance ( S , N ) ) ; } }