Convert to a string that is repetition of a substring of k length | C # 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
using System ; using System . Collections . Generic ; class GFG { static bool checkString ( String str , int k ) { int n = str . Length ; if ( n % k != 0 ) return false ; Dictionary < String , int > mp = new Dictionary < String , int > ( ) ; for ( int i = 0 ; i < n ; i += k ) { if ( ! mp . ContainsKey ( str . Substring ( i , k ) ) ) mp . Add ( str . Substring ( i , k ) , 1 ) ; else mp [ str . Substring ( i , k ) ] = mp [ str . Substring ( i , k ) ] + 1 ; } if ( mp . Count == 1 ) return true ; if ( mp . Count != 2 ) return false ; foreach ( KeyValuePair < String , int > entry in mp ) { if ( entry . Value == ( n / k - 1 ) entry . Value == 1 ) return true ; } return false ; } public static void Main ( String [ ] args ) { if ( checkString ( " abababcd " , 2 ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }