Minimum distance between duplicates in a String | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 [ i ] == S [ j ] and ( j - i ) < minDis ) { minDis = j - i ; break ; } } } if ( minDis == S . length ( ) ) return -1 ; else return minDis - 1 ; } int main ( ) { string S = " geeksforgeeks " ; int N = 13 ; cout << ( shortestDistance ( S , N ) ) ; }