String que cuando se repite exactamente K veces da una permutación de S

Dado un entero K y una string str de caracteres ingleses en minúsculas, la tarea es encontrar una string s tal que cuando s se repite exactamente K veces, da una permutación de S . Si no existe tal string, imprima -1 .
Ejemplos: 
 

Entrada: str = “aabb”, k = 2 
Salida: ab 
“ab” cuando se repite 2 veces da “abab” que es una permutación de “aabb”
Entrada: str = “aabb”, k = 3 
Salida: -1 
 

Enfoque: un enfoque eficiente es contar la frecuencia de cada carácter de la string dada. Si la frecuencia de cualquier carácter no es divisible por k , entonces la solución no es posible e imprime -1 . De lo contrario, agregue cada carácter (frecuencia / k) veces a la string resultante e imprima la string generada al final.
A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ program to find a string which when repeated
// exactly k times gives a permutation
// of the given string
#include <bits/stdc++.h>
using namespace std;
 
// Function to return a string which when repeated
// exactly k times gives a permutation of s
string K_String(string s, int k)
{
    // size of string
    int n = s.size();
 
    // to frequency of each character
    int fre[26] = { 0 };
 
    // get frequency of each character
    for (int i = 0; i < n; i++)
        fre[s[i] - 'a']++;
 
    // to store final answer
    string str = "";
 
    for (int i = 0; i < 26; i++) {
 
        // check if frequency is divisible by k
        if (fre[i] % k == 0) {
            int x = fre[i] / k;
 
            // add to answer
            while (x--) {
                str += (char)(i + 'a');
            }
        }
 
        // if frequency is not divisible by k
        else {
            return "-1";
        }
    }
 
    return str;
}
 
// Driver code
int main()
{
    string s = "aabb";
    int k = 2;
 
    // function call
    cout << K_String(s, k);
 
    return 0;
}

Java

// Java program to find a string which when repeated
// exactly k times gives a permutation
// of the given string
class GfG {
 
// Function to return a string which when repeated
// exactly k times gives a permutation of s
static String K_String(String s, int k)
{
    // size of string
    int n = s.length();
 
    // to frequency of each character
    int fre[] = new int[26];
 
    // get frequency of each character
    for (int i = 0; i < n; i++)
        fre[s.charAt(i) - 'a']++;
 
    // to store final answer
    String str = "";
 
    for (int i = 0; i < 26; i++) {
 
        // check if frequency is divisible by k
        if (fre[i] % k == 0) {
            int x = fre[i] / k;
 
            // add to answer
            while (x != 0) {
                str += (char)(i + 'a');
                x--;
            }
        }
 
        // if frequency is not divisible by k
        else {
            return "-1";
        }
    }
 
    return str;
}
 
// Driver code
public static void main(String[] args)
{
    String s = "aabb";
    int k = 2;
 
    // function call
    System.out.println(K_String(s, k));
 
}
}

Python 3

# Python 3 program to find a string
# which when repeated exactly k times
# gives a permutation of the given string
 
# Function to return a string which
# when repeated exactly k times gives
# a permutation of s
def K_String(s, k):
 
    # size of string
    n = len(s)
 
    # to frequency of each character
    fre = [0] * 26
 
    # get frequency of each character
    for i in range(n):
        fre[ord(s[i]) - ord('a')] += 1
 
    # to store final answer
    str = ""
 
    for i in range( 26) :
 
        # check if frequency is divisible by k
        if (fre[i] % k == 0) :
            x = fre[i] // k
 
            # add to answer
            while (x) :
                str += chr(i + ord('a'))
                x -= 1
 
        # if frequency is not divisible by k
        else :
            return "-1"
 
    return str
 
# Driver code
if __name__ == "__main__":
     
    s = "aabb"
    k = 2
 
    # function call
    print( K_String(s, k))
 
# This code is contributed
# by ChitraNayal

C#

// C# program to find a string which
// when repeated exactly k times gives
// a permutation of the given string
using System;
 
class GFG
{
 
// Function to return a string which
// when repeated exactly k times gives
// a permutation of s
static String K_String(String s, int k)
{
    // size of string
    int n = s.Length ;
 
    // to frequency of each character
    int []fre = new int[26];
 
    // get frequency of each character
    for (int i = 0; i < n; i++)
        fre[s[i] - 'a']++;
 
    // to store final answer
    String str = "";
 
    for (int i = 0; i < 26; i++)
    {
 
        // check if frequency is
        // divisible by k
        if (fre[i] % k == 0)
        {
            int x = fre[i] / k;
 
            // add to answer
            while (x != 0)
            {
                str += (char)(i + 'a');
                x--;
            }
        }
 
        // if frequency is not divisible by k
        else
        {
            return "-1";
        }
    }
 
    return str;
}
 
// Driver code
public static void Main(String []args)
{
    String s = "aabb";
    int k = 2;
 
    // function call
    Console.WriteLine(K_String(s, k));
}
}
 
// This code is contributed by Arnab Kundu

PHP

<?php
// PHP program to find a string which
// when repeated exactly k times gives
// a permutation of the given string
 
// Function to return a string which
// when repeated exactly k times gives
// a permutation of s
function K_String($s, $k)
{
    // size of string
    $n = strlen($s);
 
    // to frequency of each character
    $fre = $array = array_fill(0, 26, 0);
 
    // get frequency of each character
    for ($i = 0; $i < $n; $i++)
        $fre[ord($s[$i]) - ord('a')]++;
 
    // to store final answer
    $str = "";
 
    for ($i = 0; $i < 26; $i++)
    {
 
        // check if frequency is divisible by k
        if ($fre[$i] % $k == 0)
        {
            $x = $fre[$i] / $k;
 
            // add to answer
            while ($x--)
            {
                $str .= chr($i + ord('a'));
            }
        }
 
        // if frequency is not divisible by k
        else
        {
            return "-1";
        }
    }
    return $str;
}
 
// Driver code
$s = "aabb";
$k = 2;
 
// function call
echo K_String($s, $k);
 
// This code is contributed by Ryuga
?>

Javascript

<script>
// Javascript program to find a string which when repeated
// exactly k times gives a permutation
// of the given string
     
    // Function to return a string which when repeated
    // exactly k times gives a permutation of s
    function K_String(s,k)
    {
        // size of string
    let n = s.length;
   
    // to frequency of each character
    let fre = new Array(26);
    for(let i=0;i<fre.length;i++)
    {
        fre[i]=0;
    }
     
   
    // get frequency of each character
    for (let i = 0; i < n; i++)
        fre[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++;
   
    // to store final answer
    let str = "";
   
    for (let i = 0; i < 26; i++) {
   
        // check if frequency is divisible by k
        if (fre[i] % k == 0) {
            let x = Math.floor(fre[i] / k);
   
            // add to answer
            while (x != 0) {
                str += String.fromCharCode(i + 'a'.charCodeAt(0));
                x--;
            }
        }
   
        // if frequency is not divisible by k
        else {
            return "-1";
        }
    }
   
    return str;
    }
     
    // Driver code
    let s = "aabb";
    let k = 2;
     // function call
    document.write(K_String(s, k));
     
    //This code is contributed by avanitrachhadiya2155
     
</script>
Producción: 

ab

 

Publicación traducida automáticamente

Artículo escrito por rupesh_rao y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *