Open In App

Check if a string can be repeated to make another string

Given two strings a and b, the task is to check how many times the string a can be repeated to generate the string b. If b cannot be generated by repeating a then print -1.

Examples: 



Input: a = “geeks”, b = “geeksgeeks” 
Output: 2 
“geeks” can be repeated twice to generate “geeksgeeks”

Input: a = “df”, b = “dfgrt” 
Output: -1 



Approach: 

Below is the implementation of the above approach: 




// CPP implementation of the approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to return the count of repetitions
// of string a to generate string b
int getCount(string a, string b)
{
 
    // If b cannot be generated by repeating a
    if(b.length() % a.length() != 0)
        return -1;
     
    int count = b.length() /a.length();
 
    // Repeat a count number of times
    string str = "";
    for(int i = 0; i < count; i++)
    {
        str = str + a;
    }
    if(str == b)
        return count;
     
    return -1;
}
 
// Driver code
int main()
{
    string a = "geeks";
    string b = "geeksgeeks";
    cout << (getCount(a, b));
    return 0;
}
 
// This code is contributed by
// Surendra_Gangwar




// Java implementation of the approach
 
class GfG
{
 
    // Function to return the count of repetitions
    // of string a to generate string b
    static int getCount(String a, String b)
    {
        // If b cannot be generated by repeating a
        if(b.length() % a.length() != 0)
            return -1;
         
        int count = b.length() / a.length();
     
        // Repeat a count number of times
        String str = "";
        for(int i = 0; i < count; i++)
        {
            str = str + a;
        }
         
        if(str.equals(b))
            return count;
         
        return -1;
    }
 
    // Driver code
    public static void main(String []args)
    {
        String a = "geeks";
        String b = "geeksgeeks";
        System.out.println(getCount(a, b));
    }
}
     
// This code is contributed by Rituraj Jain




# Python3 implementation of the approach
 
# Function to return the count of repetitions
# of string a to generate string b
def getCount(a, b):
     
    # If b cannot be generated by repeating a
    if(len(b) % len(a) != 0):
        return -1;
     
    count = int(len(b) / len(a))
     
    # Repeat a count number of times
    a = a * count
     
    if(a == b):
        return count
     
    return -1;
 
# Driver code
if __name__ == '__main__':
    a = 'geeks'
    b = 'geeksgeeks'
    print(getCount(a, b))




// C# implementation of the approach
using System;
 
class GfG
{
 
    // Function to return the count of repetitions
    // of string a to generate string b
    static int getCount(String a, String b)
    {
        // If b cannot be generated by repeating a
        if(b.Length % a.Length != 0)
            return -1;
         
        int count = b.Length / a.Length;
     
        // Repeat a count number of times
        String str = "";
        for(int i = 0; i < count; i++)
        {
            str = str + a;
        }
         
        if(str.Equals(b))
            return count;
         
        return -1;
    }
 
    // Driver code
    public static void Main(String []args)
    {
        String a = "geeks";
        String b = "geeksgeeks";
        Console.WriteLine(getCount(a, b));
    }
}
 
// This code contributed by Rajput-Ji




<script>
 
// Javascript implementation of the approach
 
 
    // Function to return the count of repetitions
    // of string a to generate string b
    function getCount( a,  b) {
        // If b cannot be generated by repeating a
        if (b.length % a.length != 0)
            return -1;
 
        var count = parseInt(b.length / a.length);
 
        // Repeat a count number of times
        var str = "";
        for (i = 0; i < count; i++) {
            str = str + a;
        }
 
        if (str == (b))
            return count;
 
        return -1;
    }
 
    // Driver code
     
        var a = "geeks";
        var b = "geeksgeeks";
        document.write(getCount(a, b));
 
// This code is contributed by todaysgaurav
 
</script>




<?php
// PHP implementation of the approach
 
// Function to return the count of repetitions
// of string a to generate string b
function getCount($a, $b)
{
     
    // If b cannot be generated by repeating a
    if(strlen($b) % strlen($a) != 0)
        return -1;
     
    $count = floor(strlen($b) / strlen($a));
     
    // Repeat a count number of times
    // Repeat a count number of times
    $str = "";
    for($i = 0; $i < $count; $i++)
    {
        $str = $str . $a ;
    }
     
    if(strcmp($a,$b))
        return $count;
     
    return -1;
}
 
// Driver code
$a = 'geeks';
$b = 'geeksgeeks';
echo getCount($a, $b);
 
// This code is contributed by Ryuga
?>

Output
2







Time Complexity: O(n/m), where m and n are the lengths of the given strings a and b respectively.
Auxiliary Space: O(n), where n is the length of the string.

Approach:

Below is the implementation of the above approach:




#include <iostream>
#include <stack>
using namespace std;
 
int count_repetitions(string a, string b) {
    int n = a.length();
    int m = b.length();
    if (m % n != 0) {
        return -1;
    }
    int repetitions = m / n;
    stack<string> s;
    for (int i = 0; i < repetitions; i++) {
        s.push(b.substr(i*n, n));
    }
    string str = "";
    while (!s.empty()) {
        str += s.top();
        s.pop();
    }
    if (str == b) {
        return repetitions;
    } else {
        return -1;
    }
}
 
int main() {
    string a = "geeks";
    string b = "geeksgeeks";
    cout <<  count_repetitions(a, b) << endl;
    return 0;
}




import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        String a = "geeks";
        String b = "geeksgeeks";
        System.out.println(countRepetitions(a, b));
    }
 
    // Function to count the number of times string 'a' is repeated to form string 'b'
    public static int countRepetitions(String a, String b) {
        int n = a.length();
        int m = b.length();
 
        // If the length of string 'b' is not a multiple of the length of string 'a', it's not possible to repeat 'a' to form 'b'
        if (m % n != 0) {
            return -1;
        }
 
        // Calculate the number of repetitions required to form 'b' from 'a'
        int repetitions = m / n;
 
        // Use a stack to store the individual substrings of 'b' that correspond to each repetition of 'a'
        Stack<String> stack = new Stack<>();
        for (int i = 0; i < repetitions; i++) {
            // Push each substring into the stack by extracting it from 'b'
            stack.push(b.substring(i * n, (i + 1) * n));
        }
 
        // Build a new string by popping the substrings from the stack in reverse order
        StringBuilder str = new StringBuilder();
        while (!stack.isEmpty()) {
            str.append(stack.pop());
        }
 
        // If the final concatenated string matches 'b', it means 'a' is repeated 'repetitions' times to form 'b'
        // Return the number of repetitions, else return -1
        if (str.toString().equals(b)) {
            return repetitions;
        } else {
            return -1;
        }
    }
}




def count_repetitions(a, b):
    n = len(a)
    m = len(b)
 
    # Check if the length of 'b' is a multiple of the length of 'a'
    if m % n != 0:
        return -1
 
    repetitions = m // n
    stack = []
 
    # Split 'b' into 'repetitions' parts and store them in the stack
    for i in range(repetitions):
        stack.append(b[i * n: (i + 1) * n])
 
    str_result = ""
 
    # Pop elements from the stack and append them to 'str_result'
    while stack:
        str_result += stack.pop()
 
    # Compare 'str_result' with 'b' to check if they are the same
    if str_result == b:
        return repetitions
    else:
        return -1
 
 
if __name__ == "__main__":
    a = "geeks"
    b = "geeksgeeks"
    print(count_repetitions(a, b))
 
 
# This code is contributed by shivamgupta0987654321




using System;
 
public class GFG
{
    // Function to count repetitions of 'a' in 'b'
    public static int CountRepetitions(string a, string b)
    {
        int n = a.Length;
        int m = b.Length;
 
        // Check if the length of 'b' is a multiple of the length of 'a'
        if (m % n != 0)
        {
            return -1;
        }
 
        int repetitions = m / n;
        var stack = new System.Collections.Generic.Stack<string>();
 
        // Split 'b' into 'repetitions' parts and store them in the stack
        for (int i = 0; i < repetitions; i++)
        {
            stack.Push(b.Substring(i * n, n));
        }
 
        string strResult = "";
 
        // Pop elements from the stack and append them to 'strResult'
        while (stack.Count > 0)
        {
            strResult += stack.Pop();
        }
 
        // Compare 'strResult' with 'b' to check if they are the same
        if (strResult == b)
        {
            return repetitions;
        }
        else
        {
            return -1;
        }
    }
 
    public static void Main(string[] args)
    {
        string a = "geeks";
        string b = "geeksgeeks";
        Console.WriteLine(CountRepetitions(a, b));
    }
}
// This code is contributed by rambabuguphka




function countRepetitions(a, b) {
    const n = a.length;
    const m = b.length;
 
    // Check if the length of 'b' is a multiple of the length of 'a'
    if (m % n !== 0) {
        return -1;
    }
 
    const repetitions = m / n;
    const stack = [];
 
    // Split 'b' into 'repetitions' parts and store them in the stack
    for (let i = 0; i < repetitions; i++) {
        stack.push(b.substring(i * n, (i + 1) * n));
    }
 
    let strResult = "";
 
    // Pop elements from the stack and append them to 'strResult'
    while (stack.length > 0) {
        strResult += stack.pop();
    }
 
    // Compare 'strResult' with 'b' to check if they are the same
    if (strResult === b) {
        return repetitions;
    } else {
        return -1;
    }
}
 
const a = "geeks";
const b = "geeksgeeks";
console.log(countRepetitions(a, b));
 
// This code is contributed by shivamgupta0987654321

Output
2








Time Complexity: O(m), where m is the length of the string b.

Auxiliary Space: O(m/n + m), where n is the length of the string a and m is the length of the string b.


Article Tags :