Dada una string S de tamaño N , que consta de dígitos [0 – 9] y el carácter ‘.’ , la tarea es imprimir la string que se puede obtener presionando el teclado móvil en la secuencia dada.
Nota: ‘.’ representa un descanso mientras se escribe.
A continuación se muestra la imagen para representar los caracteres asociados con cada número en el teclado.
Ejemplos:
Entrada: S = «234»
Salida: ADG
Explicación:
Al presionar las teclas 2, 3 y 4 una vez, la string resultante es «ADG».Entrada: S = “22.22”
Salida: BB
Explicación:
Presionar la tecla 2 dos veces da B, y luego presionar nuevamente la tecla dos veces da B. Por lo tanto, la string resultante es “BB”.
Enfoque: el problema dado se puede resolver almacenando las asignaciones de teclados móviles en una array y luego atravesar la string S y convertirla en su string equivalente. Siga los pasos a continuación para resolver el problema:
- Inicialice una string vacía, diga ans para almacenar el resultado requerido.
- Almacena la string asociada a cada tecla del teclado del móvil en un array nums[] de forma que nums[i] representa el conjunto de caracteres al pulsar el dígito i .
- Recorra la string S dada usando la variable i y realice los siguientes pasos:
- Si S[i] es igual a ‘.’ , luego incremente i en 1 y continúe con la siguiente iteración .
- De lo contrario, inicialice una variable cnt como 0 para almacenar el recuento de los mismos caracteres.
- Iterar hasta que S[i] sea igual a S[i + 1] y en cada iteración verificar las siguientes condiciones:
- Si cnt es igual a 2 y S[i] es 2, 3, 4, 5, 6 u 8, salga del ciclo porque las teclas: 2, 3, 4, 5, 6 y 8 contienen el mismo número de caracteres, es decir, 3.
- Si cnt es igual a 3 y S[i] es 7 o 9, salga del bucle porque las teclas: 7 y 9 contienen el mismo número de caracteres, es decir, 4.
- Incremente el valor de cnt e i en 1.
- Si S[i] es 7 o 9, agregue el carácter nums[str[i]][cnt%4] a la string ans .
- De lo contrario, agregue el carácter nums[str[i]][cnt%3] a la string ans .
- Incrementa el valor de i en 1.
- Después de completar los pasos anteriores, imprima la string de valor como resultado.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to convert mobile numeric // keypad sequence into its equivalent // string void printSentence(string str) { // Store the mobile keypad mappings char nums[][5] = { "", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ" }; // Traverse the string str int i = 0; while (str[i] != '\0') { // If the current character is // '.', then continue to the // next iteration if (str[i] == '.') { i++; continue; } // Stores the number of // continuous clicks int count = 0; // Iterate a loop to find the // count of same characters while (str[i + 1] && str[i] == str[i + 1]) { // 2, 3, 4, 5, 6 and 8 keys will // have maximum of 3 letters if (count == 2 && ((str[i] >= '2' && str[i] <= '6') || (str[i] == '8'))) break; // 7 and 9 keys will have // maximum of 4 keys else if (count == 3 && (str[i] == '7' || str[i] == '9')) break; count++; i++; // Handle the end condition if (str[i] == '\0') break; } // Check if the current pressed // key is 7 or 9 if (str[i] == '7' || str[i] == '9') { cout << nums[str[i] - 48][count % 4]; } // Else, the key pressed is // either 2, 3, 4, 5, 6 or 8 else { cout << nums[str[i] - 48][count % 3]; } i++; } } // Driver Code int main() { string str = "234"; printSentence(str); return 0; }
Java
// java program for the above approach import java.io.*; import java.lang.*; import java.util.*; public class GFG { // Function to convert mobile numeric // keypad sequence into its equivalent // string static void printSentence(String S) { // Store the mobile keypad mappings String nums[] = { "", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ" }; char str[] = S.toCharArray(); // Traverse the string str int i = 0; while (i < str.length) { // If the current character is // '.', then continue to the // next iteration if (str[i] == '.') { i++; continue; } // Stores the number of // continuous clicks int count = 0; // Iterate a loop to find the // count of same characters while (i + 1 < str.length && str[i] == str[i + 1]) { // 2, 3, 4, 5, 6 and 8 keys will // have maximum of 3 letters if (count == 2 && ((str[i] >= '2' && str[i] <= '6') || (str[i] == '8'))) break; // 7 and 9 keys will have // maximum of 4 keys else if (count == 3 && (str[i] == '7' || str[i] == '9')) break; count++; i++; // Handle the end condition if (i == str.length) break; } // Check if the current pressed // key is 7 or 9 if (str[i] == '7' || str[i] == '9') { System.out.print( nums[str[i] - 48].charAt(count % 4)); } // Else, the key pressed is // either 2, 3, 4, 5, 6 or 8 else { System.out.print( nums[str[i] - 48].charAt(count % 3)); } i++; } } // Driver Code public static void main(String[] args) { String str = "234"; printSentence(str); } } // This code is contributed by Kingash.
Python3
# Python3 program for the above approach # Function to convert mobile numeric # keypad sequence into its equivalent # string def printSentence(str1): # Store the mobile keypad mappings nums = [ "", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ" ] # Traverse the string str1 i = 0 while (i < len(str1)): # If the current character is # '.', then continue to the # next iteration if (str1[i] == '.'): i += 1 continue # Stores the number of # continuous clicks count = 0 # Iterate a loop to find the # count of same characters while (i + 1 < len(str1) and str1[i + 1] and str1[i] == str1[i + 1]): # 2, 3, 4, 5, 6 and 8 keys will # have maximum of 3 letters if (count == 2 and ((str1[i] >= '2' and str1[i] <= '6') or (str1[i] == '8'))): break # 7 and 9 keys will have # maximum of 4 keys elif (count == 3 and (str1[i] == '7' or str1[i] == '9')): break count += 1 i += 1 # Handle the end condition if (i < len(str)): break # Check if the current pressed # key is 7 or 9 if (str1[i] == '7' or str1[i] == '9'): print(nums[ord(str1[i]) - 48][count % 4], end = "") # Else, the key pressed is # either 2, 3, 4, 5, 6 or 8 else: print(nums[ord(str1[i]) - 48][count % 3], end = "") i += 1 # Driver Code if __name__ == '__main__': str1 = "234" printSentence(str1) # This code is contributed by bgangwar59
C#
// C# program for the above approach using System; public class GFG { // Function to convert mobile numeric // keypad sequence into its equivalent // string static void printSentence(string S) { // Store the mobile keypad mappings string[] nums = { "", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ" }; char[] str = S.ToCharArray(); // Traverse the string str int i = 0; while (i < str.Length) { // If the current character is // '.', then continue to the // next iteration if (str[i] == '.') { i++; continue; } // Stores the number of // continuous clicks int count = 0; // Iterate a loop to find the // count of same characters while (i + 1 < str.Length && str[i] == str[i + 1]) { // 2, 3, 4, 5, 6 and 8 keys will // have maximum of 3 letters if (count == 2 && ((str[i] >= '2' && str[i] <= '6') || (str[i] == '8'))) break; // 7 and 9 keys will have // maximum of 4 keys else if (count == 3 && (str[i] == '7' || str[i] == '9')) break; count++; i++; // Handle the end condition if (i == str.Length) break; } // Check if the current pressed // key is 7 or 9 if (str[i] == '7' || str[i] == '9') { Console.Write(nums[str[i] - 48][count % 4]); } // Else, the key pressed is // either 2, 3, 4, 5, 6 or 8 else { Console.Write(nums[str[i] - 48][count % 3]); } i++; } } // Driver Code public static void Main(string[] args) { string str = "234"; printSentence(str); } } // This code is contributed by ukasp.
Javascript
<script> // Javascript program for the above approach // Function to convert mobile numeric // keypad sequence into its equivalent // string function printSentence(S) { // Store the mobile keypad mappings let nums = [ "", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"]; let str = S.split(""); // Traverse the string str let i = 0; while (i < str.length) { // If the current character is // '.', then continue to the // next iteration if (str[i] == '.') { i++; continue; } // Stores the number of // continuous clicks let count = 0; // Iterate a loop to find the // count of same characters while (i + 1 < str.length && str[i] == str[i + 1]) { // 2, 3, 4, 5, 6 and 8 keys will // have maximum of 3 letters if (count == 2 && ((str[i] >= '2' && str[i] <= '6') || (str[i] == '8'))) break; // 7 and 9 keys will have // maximum of 4 keys else if (count == 3 && (str[i] == '7' || str[i] == '9')) break; count++; i++; // Handle the end condition if (i == str.length) break; } // Check if the current pressed // key is 7 or 9 if (str[i] == '7' || str[i] == '9') { document.write( nums[str[i].charCodeAt(0) - 48][count % 4]); } // Else, the key pressed is // either 2, 3, 4, 5, 6 or 8 else { document.write( nums[str[i].charCodeAt(0) - 48][count % 3]); } i++; } } // Driver Code let str = "234"; printSentence(str); // This code is contributed by _saurabh_jaiswal. </script>
ADG
Complejidad temporal: O(N)
Espacio auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por avllikhita y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA