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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkString ( string str , long k ) { int n = str . length ( ) ; if ( n % k != 0 ) return false ; unordered_map < string , int > mp ; for ( int i = 0 ; i < n ; i += k ) mp [ str . substr ( i , k ) ] ++ ; if ( mp . size ( ) == 1 ) return true ; if ( mp . size ( ) != 2 ) return false ; if ( ( mp . begin ( ) -> second == ( n / k - 1 ) ) || mp . begin ( ) -> second == 1 ) return true ; return false ; } int main ( ) { checkString ( " abababcd " , 2 ) ? cout << " Yes " : cout << " No " ; return 0 ; }