Cambiar string a un nuevo conjunto de caracteres

Dado un juego de caracteres de 26 letras, que es equivalente al juego de caracteres del alfabeto inglés, es decir (abcd….xyz) y actúa como una relación. También nos dan varias oraciones y tenemos que traducirlas con la ayuda de un nuevo conjunto de caracteres dado.

Ejemplos: 

New character set : qwertyuiopasdfghjklzxcvbnm
Input : "utta"
Output : geek

Input : "egrt"
Output : code

La idea detrás de la conversión del nuevo conjunto de caracteres es usar hashing. Realice el hash del nuevo conjunto de caracteres donde el elemento del conjunto es el índice y su posición será el nuevo valor alfabético. 

Enfoque1: 

Given New character set = "qwertyuiopasdfghjklzxcvbnm" 
First character is q, during hashing we will place 'a' (for position )
at index q i.e. (17th).
After hashing our new character set is "kxvmcnophqrszyijadlegwbuft".
For input "egrt" = 
      hash[e -'a'] = c 
      hash[g -'a'] = o 
      hash[r -'a'] = d 
      hash[t -'a'] = e
For "egrt" is equivalent to "code".

Implementación:

C++

// CPP program to change the sentence
// with virtual dictionary 
#include<bits/stdc++.h>
using namespace std;
  
// Converts str to given character set
void conversion(char charSet[], string &str)
{ 
    int n = str.length();
  
    // hashing for new character set
    char hashChar[26];
    for (int i = 0; i < 27; i++)    
        hashChar[charSet[i]-'a'] = 'a' + i;    
      
    // conversion of new character set
    for (int i = 0; i < n; i++)
        str[i] = hashChar[str[i]-'a'];
}
  
// Driver code
int main()
{
    char charSet[27] = "qwertyuiopasdfghjklzxcvbnm";
    string str = "egrt"; 
    conversion(charSet, str);
    cout << str;
    return 0;
}

Java

// Java program to change the sentence
// with virtual dictionary 
class GFG {
  
// Converts str to given character set
    static String conversion(char charSet[], String str) {
        int n = str.length();
  
        // hashing for new character set
        char hashChar[] = new char[26];
        for (int i = 0; i < 26; i++) {
            int ch = Math.abs(charSet[i] - 'a');
            hashChar[ch] = (char) ('a' + i);
        }
  
        // conversion of new character set
        String s="";
        for (int i = 0; i < n; i++) {
            s += hashChar[str.charAt(i) - 'a'];
        }
        return s;
    }
  
// Driver code
    public static void main(String[] args) {
        char charSet[] = "qwertyuiopasdfghjklzxcvbnm".toCharArray();
        String str = "egrt";
        str = conversion(charSet, str);
        System.out.println(str);
// This code is contributed by princiRaj1992
    }
}

Python3

# Python3 program to change the sentence
# with virtual dictionary
from string import ascii_lowercase
  
# Function to convert the string using the given charset
def conversion(char_set: str, string: str) -> str:
    #hashing for new character set
    hash_char = dict()
  
    for alphabet, new_char in zip(ascii_lowercase, char_set):
        hash_char[new_char] = alphabet
  
    # conversion of new character set
    string2 = ""
    for i in string:
        string2 += hash_char[i]
  
    return string2
  
# Driver Code
if __name__ == "__main__":
    char_set = "qwertyuiopasdfghjklzxcvbnm"
    string = "egrt"
  
    print(conversion(char_set, string))
  
    # This code is contributed by kraanzu.

C#

// C# program to change the sentence
// with virtual dictionary 
using System;
      
class GFG 
{
  
    // Converts str to given character set
    static String conversion(char []charSet, 
                             String str) 
    {
        int n = str.Length;
  
        // hashing for new character set
        char []hashChar = new char[26];
        for (int i = 0; i < 26; i++) 
        {
            int ch = Math.Abs(charSet[i] - 'a');
            hashChar[ch] = (char) ('a' + i);
        }
  
        // conversion of new character set
        String s = "";
        for (int i = 0; i < n; i++) 
        {
            s += hashChar[str[i] - 'a'];
        }
        return s;
    }
  
    // Driver code
    public static void Main(String[] args) 
    {
        char []charSet = "qwertyuiopasdfghjklzxcvbnm".ToCharArray();
        String str = "egrt";
        str = conversion(charSet, str);
        Console.WriteLine(str);
    }
}
  
// This code is contributed by Princi Singh

Javascript

<script>
// Javascript program to change the sentence
// with virtual dictionary 
  
// Converts str to given character set
function conversion(charSet, str)
{ 
    var n = str.length;
  
    // hashing for new character set
    var hashChar = Array(26);
    for (var i = 0; i < 26; i++)    
     {
       var ch = Math.abs(charSet[i].charCodeAt(0)-
        'a'.charCodeAt(0));
        hashChar[ch] = 
        String.fromCharCode('a'.charCodeAt(0) + i);   
} 
    var s = "";
      
    // conversion of new character set
    for (var i = 0; i < n; i++)
        s += (hashChar[str[i].charCodeAt(0)-'a'.charCodeAt(0)]);
    return s;
}
  
// Driver code
var charSet = "qwertyuiopasdfghjklzxcvbnm".split('');
var str = "egrt"; 
str = conversion(charSet, str);
document.write( str);
  
// This code is contributed by importantly.
</script>
Producción

code

Complejidad de tiempo: O(N) donde N es la longitud de la string.
Espacio Auxiliar: O(1) 

Enfoque2: 

  1. Inicialice dos strings, una con el conjunto real de alfabetos y otra con uno modificado. 
  2. Obtenga la string que se va a convertir del usuario. 
  3. Recupere el primer elemento de la string, busque su índice en el conjunto modificado de alfabetos (p. ej.: 0 para ‘q’). 
  4. Encuentre el elemento del mismo índice en el conjunto real de alfabetos y concatene con la string de resultado. 
  5. Repita los pasos anteriores para todos los elementos restantes de la string de entrada. 
  6. Devuelve la string de resultado. 

C++

// CPP program to change the sentence
// with virtual dictionary
#include <bits/stdc++.h>
using namespace std;
  
// Converts str to given character set
string conversion(string charSet, string str)
{
    string alphabets = "abcdefghijklmnopqrstuvwxyz";
    string s2 = "";
  
    for (char i : str) {
        s2 += alphabets[charSet.find_first_of(i)];
    }
  
    return s2;
}
  
// Driver code
int main()
{
    string charSet = "qwertyuiopasdfghjklzxcvbnm";
    string str = "egrt";
    cout << conversion(charSet, str);
    return 0;
}

Java

// Java program to change the sentence
// with virtual dictionary 
  
class GFG 
{
    static char[] alphabets = "abcdefghijklmnopqrstuvwxyz".toCharArray();
  
    // function for converting the string
    static String conversion(String charSet, char[] str1)
    {
        String s2 = "";
        for (char i : str1)
          
            // find the index of each element of the
            // string in the modified set of alphabets
            // replace the element with the one having the
            // same index in the actual set of alphabets
            s2 += alphabets[charSet.indexOf(i)];
  
        return s2;
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        String charSet = "qwertyuiopasdfghjklzxcvbnm";
        String str1 = "egrt";
        System.out.print(conversion(charSet, str1.toCharArray()));
    }
}
  
// This code is contributed by PrinciRaj1992

Python3

# Python3 program to change the sentence
#  with virtual dictionary 
  
#function for converting the string
def conversion(charSet,str1):
    s2=""
    for i in str1:
        # find the index of each element of the
        # string in the modified set of alphabets
        # replace the element with the one having the
        # same index in the actual set of alphabets
        s2 += alphabets[charSet.index(i)]
          
    return s2
  
# Driver Code
if __name__=='__main__':
    alphabets = "abcdefghijklmnopqrstuvwxyz"
    charSet= "qwertyuiopasdfghjklzxcvbnm"
    str1 = "egrt"
    print(conversion(charSet,str1))
  
#This code is contributed by PradeepEswar

C#

// C# program to change the sentence
// with virtual dictionary 
using System;
  
class GFG 
{
    static char[] alphabets = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
  
    // function for converting the string
    static String conversion(String charSet, char[] str1)
    {
        String s2 = "";
        foreach (char i in str1)
          
            // find the index of each element of the
            // string in the modified set of alphabets
            // replace the element with the one having the
            // same index in the actual set of alphabets
            s2 += alphabets[charSet.IndexOf(i)];
  
        return s2;
    }
  
    // Driver Code
    public static void Main(String[] args)
    {
        String charSet = "qwertyuiopasdfghjklzxcvbnm";
        String str1 = "egrt";
        Console.Write(conversion(charSet, str1.ToCharArray()));
    }
}
  
// This code is contributed by Rajput-Ji

Javascript

<script>
      // JavaScript program to change the sentence
      // with virtual dictionary
      var alphabets = "abcdefghijklmnopqrstuvwxyz".split("");
  
      // function for converting the string
      function conversion(charSet, str1) {
        var s2 = "";
        str1.forEach((i) => {
          // find the index of each element of the
          // string in the modified set of alphabets
          // replace the element with the one having the
          // same index in the actual set of alphabets
          s2 = s2 + alphabets[charSet.indexOf(i)];
        });
        return s2;
      }
  
      // Driver Code
      var charSet = "qwertyuiopasdfghjklzxcvbnm";
      var str1 = "egrt";
      document.write(conversion(charSet, str1.split("")));
        
      // This code is contributed by rdtank.
    </script>
Producción

code

Complejidad de tiempo: O(N) donde N es la longitud de la string.
Espacio Auxiliar: O(1).

Publicación traducida automáticamente

Artículo escrito por anand_pal 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 *