Convert to a string that is repetition of a substring of k length | Java program to check if a string can be converted to a string that has repeated substrings of length k . ; Returns true if str can be converted to a string with k repeated substrings after replacing k characters . ; Length of string must be a multiple of k ; Map to store strings of length k and their counts ; If string is already a repetition of k substrings , return true . ; If number of distinct substrings is not 2 , then not possible to replace a string . ; One of the two distinct must appear exactly once . Either the first entry appears once , or it appears n / k - 1 times to make other substring appear once . ; Driver code
import java . util . HashMap ; import java . util . Iterator ; class GFG { static boolean checkString ( String str , int k ) { int n = str . length ( ) ; if ( n % k != 0 ) return false ; HashMap < String , Integer > mp = new HashMap < > ( ) ; try { for ( int i = 0 ; i < n ; i += k ) mp . put ( str . substring ( i , k ) , mp . get ( str . substring ( i , k ) ) == null ? 1 : mp . get ( str . substring ( i , k ) ) + 1 ) ; } catch ( Exception e ) { } if ( mp . size ( ) == 1 ) return true ; if ( mp . size ( ) != 2 ) return false ; HashMap . Entry < String , Integer > entry = mp . entrySet ( ) . iterator ( ) . next ( ) ; if ( entry . getValue ( ) == ( n / k - 1 ) || entry . getValue ( ) == 1 ) return true ; return false ; } public static void main ( String [ ] args ) { if ( checkString ( " abababcd " , 2 ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }