Descifrar la string de acuerdo con el algoritmo dado

Dada la string encriptada str que consta de caracteres alfabéticos y numéricos, la tarea es descifrar la string y encontrar el mensaje encriptado. 
Para descifrar el mensaje, encuentre cada grupo de caracteres numéricos que representan un solo carácter alfabético que se puede obtener calculando el módulo del número con 26 y el valor encontrado del rango [0, 25] se puede mapear con los caracteres [ ‘a’, ‘z’]. 
Por ejemplo, si str = «32ytAAcV4ui30hf10hj18» , los grupos de caracteres numéricos serán {32, 4, 30, 10, 18}, lo que da {6, 4, 4, 10, 18} después de realizar el módulo con 26 y se puede asignar a {‘g’, ‘e’, ​​’e’, ​​’k’, ‘s’}
Ejemplos: 

Entrada: str = «this50hi4huji70» 
Salida: geeks
Entrada: str = «a1s2d3f3» 
Salida: bcdd 

Enfoque: la idea es recorrer cada carácter uno por uno en una string, luego verificar si es un carácter numérico o no. Si es así, concatenarlo en una string. Finalmente, módulo esa string de números con 26. 
Al realizar la operación de módulo, no podemos simplemente hacer x % 26 ya que el número puede ser demasiado grande y dará como resultado un desbordamiento de enteros. 
Para manejar esto, procesaremos todos los dígitos uno por uno y usaremos la propiedad que 
(A * B) mod C = ((A mod C) * (B mod C)) mod C
Luego, finalmente decodificaremos cada entero a carácter por 0, 1, 2, 3, …25 a ‘a’, ‘b’, ‘c’, …’z’, concatenar todos los caracteres e imprimir el resultado final.
A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
const int MOD = 26;
 
// Function that returns (num % 26)
int modulo_by_26(string num)
{
    // Initialize result
    int res = 0;
 
    // One by one process all digits of 'num'
    for (int i = 0; i < num.length(); i++)
        res = (res * 10 + (int)num[i] - '0') % MOD;
 
    return res;
}
 
// Function to return the decrypted string
string decrypt_message(string s)
{
 
    // To store the final decrypted answer
    string decrypted_str = "";
 
    string num_found_so_far = "";
 
    // One by one check for each character
    // if it is a numeric character
    for (int i = 0; i < s.length(); ++i) {
 
        if (s[i] >= '0' && s[i] <= '9') {
            num_found_so_far += s[i];
        }
        else if (num_found_so_far.length() > 0) {
 
            // Modulo the number found in the string by 26
            decrypted_str += 'a'
                             + modulo_by_26(num_found_so_far);
 
            num_found_so_far = "";
        }
    }
 
    if (num_found_so_far.length() > 0) {
        decrypted_str += 'a'
                         + modulo_by_26(num_found_so_far);
    }
 
    return decrypted_str;
}
 
// Driver code
int main()
{
    string s = "32ytAAcV4ui30hf10hj18";
 
    // Print the decrypted string
    cout << decrypt_message(s);
 
    return 0;
}

Java

// Java implementation of the approach
import java.util.*;
 
class GFG{
     
static int MOD = 26;
 
// Function that returns (num % 26)
static int modulo_by_26(String num)
{
     
    // Initialize result
    int res = 0;
 
    // One by one process all digits of 'num'
    for(int i = 0; i < num.length(); i++)
    {
       res = ((res * 10 +
              (int)num.charAt(i) - '0') % MOD);
    }
    return res;
}
 
// Function to return the decrypted String
static String decrypt_message(String s)
{
 
    // To store the final decrypted answer
    String decrypted_str = "";
    String num_found_so_far = "";
 
    // One by one check for each character
    // if it is a numeric character
    for(int i = 0; i < s.length(); ++i)
    {
       if (s.charAt(i) >= '0' && s.charAt(i) <= '9')
       {
           num_found_so_far += s.charAt(i);
       }
       else if (num_found_so_far.length() > 0)
       {
            
           // Modulo the number found in the String by 26
           decrypted_str += (char)('a' +
                             modulo_by_26(num_found_so_far));
           num_found_so_far = "";
       }
    }
    if (num_found_so_far.length() > 0)
    {
        decrypted_str += (char)('a' +
                          modulo_by_26(num_found_so_far));
    }
    return decrypted_str;
}
 
// Driver code
public static void main(String[] args)
{
    String s = "32ytAAcV4ui30hf10hj18";
 
    // Print the decrypted string
    System.out.print(decrypt_message(s));
}
}
 
// This code is contributed by amal kumar choubey

Python3

# Python3 implementation of
# the approach
MOD = 26
 
# Function that returns
# (num % 26)
def modulo_by_26(num):
 
    # Initialize result
    res = 0
 
    # One by one process all
    # digits of 'num'
    for i in range(len(num)):
        res = ((res * 10 + ord(num[i]) -
                ord('0')) % MOD)
 
    return res
 
# Function to return the
# decrypted string
def decrypt_message(s):
 
    # To store the final
    # decrypted answer
    decrypted_str = ""
 
    num_found_so_far = ""
 
    # One by one check for
    # each character if it
    # is a numeric character
    for i in range(len(s)):
 
        if (s[i] >= '0' and
            s[i] <= '9'):
            num_found_so_far += s[i]
        elif (len(num_found_so_far) > 0):
 
            # Modulo the number found
            # in the string by 26
            decrypted_str += chr(ord('a') +
                            (modulo_by_26(num_found_so_far)))
 
            num_found_so_far = ""
 
    if (len(num_found_so_far) > 0):
        decrypted_str += chr(ord('a') +
                        (modulo_by_26(num_found_so_far)))
 
    return decrypted_str
 
# Driver code
if __name__ == "__main__":
 
    s = "32ytAAcV4ui30hf10hj18"
 
    # Print the decrypted string
    print(decrypt_message(s))
 
# This code is contributed by Chitranayal

C#

// C# implementation of the approach
using System;
class GFG{
     
static int MOD = 26;
 
// Function that returns (num % 26)
static int modulo_by_26(String num)
{
     
    // Initialize result
    int res = 0;
 
    // One by one process all digits of 'num'
    for(int i = 0; i < num.Length; i++)
    {
        res = ((res * 10 +
               (int)num[i] - '0') % MOD);
    }
    return res;
}
 
// Function to return the decrypted String
static String decrypt_message(String s)
{
 
    // To store the readonly decrypted answer
    String decrypted_str = "";
    String num_found_so_far = "";
 
    // One by one check for each character
    // if it is a numeric character
    for(int i = 0; i < s.Length; ++i)
    {
        if (s[i] >= '0' && s[i] <= '9')
        {
            num_found_so_far += s[i];
        }
        else if (num_found_so_far.Length > 0)
        {
                 
            // Modulo the number found
            // in the String by 26
            decrypted_str += (char)('a' +
                              modulo_by_26(num_found_so_far));
            num_found_so_far = "";
        }
    }
    if (num_found_so_far.Length > 0)
    {
        decrypted_str += (char)('a' +
                          modulo_by_26(num_found_so_far));
    }
    return decrypted_str;
}
 
// Driver code
public static void Main(String[] args)
{
    String s = "32ytAAcV4ui30hf10hj18";
 
    // Print the decrypted string
    Console.Write(decrypt_message(s));
}
}
 
// This code is contributed by amal kumar choubey

Javascript

<script>
 
// JavaScript implementation of the approach
 
let MOD = 26;
 
// Function that returns (num % 26)
function modulo_by_26(num)
{
    // Initialize result
    let res = 0;
  
    // One by one process all digits of 'num'
    for(let i = 0; i < num.length; i++)
    {
       res = ((res * 10 +
              num[i].charCodeAt(0) - '0'.charCodeAt(0)) % MOD);
    }
    return res;
}
 
// Function to return the decrypted String
function decrypt_message(s)
{
    // To store the final decrypted answer
    let decrypted_str = "";
    let num_found_so_far = "";
  
    // One by one check for each character
    // if it is a numeric character
    for(let i = 0; i < s.length; ++i)
    {
       if (s[i].charCodeAt(0) >= '0'.charCodeAt(0) &&
       s[i].charCodeAt(0) <= '9'.charCodeAt(0))
       {
           num_found_so_far += s[i];
       }
       else if (num_found_so_far.length > 0)
       {
             
           // Modulo the number found in the String by 26
           decrypted_str += String.fromCharCode('a'.charCodeAt(0) +
                             modulo_by_26(num_found_so_far));
           num_found_so_far = "";
       }
    }
    if (num_found_so_far.length > 0)
    {
        decrypted_str += String.fromCharCode('a'.charCodeAt(0) +
                          modulo_by_26(num_found_so_far));
    }
    return decrypted_str;
}
 
// Driver code
 
let s = "32ytAAcV4ui30hf10hj18";
 
// Print the decrypted string
document.write(decrypt_message(s));
     
 
// This code is contributed by rag2127
 
</script>
Producción: 

geeks

 

Complejidad temporal: O(N)
Espacio auxiliar: O(N)

Publicación traducida automáticamente

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