Repetition of k length substring

PROBLEM :
Given a string 's', your task is to complete the function checkString which returns true if it is possible to convert 's' to a string that is repetition of a substring with 'k' characters else returns false, where in order to convert we can replace one substring of length k with k characters.

Examples:

Input: str = "abcbedabcabc",  k = 3
Output: 1
Replace "bed" with "abc" so that the
whole string becomes repetition of "abc".

Input: str = "bcacbcac", k = 2
Output: 0

Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains 2 lines. The first line of each test case contains a string s. The second line of each test case contains an integer n.

Output:
For each test case in a new line output will be 1 if it is possible to convert the string else 0.

Constraints:
1<=T<=100
1< |Length of string| <=100
1<=N<=10

Example(To be used only for expected output):
Input:
2
abcbedabcabc
3
bcacbcac
2

Output:
1
0

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*You are required to complete below method */

bool checkString(string str, int k)
{
    int len=str.length() ;
   
    if(len%k!=0)
        return false ;
       
    map<string,int> check ;
    for(int i=0;i<len;i+=k)
        check[str.substr(i, k)]++ ;
       
    if(check.size()==1)
        return true ;
   
    if(check.size()!=2)
        return false ;
       
    if(check.begin()->second==len/k-1||check.begin()->second==1)
        return true ;
       
    return false ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )