Dada una string S que consta de N alfabetos en minúsculas, la tarea es modificar la string S reemplazando cada carácter con el alfabeto cuya distancia circular desde el carácter es igual a la frecuencia del carácter en S .
Ejemplos:
Entrada: S = “geeks”
Salida: hgglt
Explicación:
Las siguientes modificaciones se realizan en la string S:
- La frecuencia de ‘g’ en la string es 1. Por lo tanto, ‘g’ se reemplaza por ‘h’.
- La frecuencia de ‘e’ en la string es 2. Por lo tanto, ‘e’ se reemplaza por ‘g’.
- La frecuencia de ‘e’ en la string es 2. Por lo tanto, ‘e’ se reemplaza por ‘g’.
- La frecuencia de ‘k’ en la string es 1. Por lo tanto, ‘k’ se convierte en ‘k’ + 1 = ‘l’.
- La frecuencia de ‘s’ en la string es 1. Por lo tanto, ‘s’ se convierte en ‘s’ + 1 = ‘t’.
Por lo tanto, la string S modificada es «hgglt».
Entrada: S = “jazz”
Salida: “kbbb”
Enfoque: el problema dado se puede resolver manteniendo la array de frecuencias que almacena las ocurrencias de cada carácter en la string . Siga los pasos a continuación para resolver el problema:
- Inicialice una array , freq[26] inicialmente con todos los elementos como 0 para almacenar la frecuencia de cada carácter de la string .
- Recorre la string S dada e incrementa la frecuencia de cada carácter S[i] en 1 en la array freq[] .
- Recorra la string S usó la variable i y realizó los siguientes pasos:
- Almacene el valor que se agregará a S[i] en una variable, agregue como (freq[i] % 26) .
- Si, después de agregar el valor de add a S[i] , S[i] no excede el carácter z , entonces actualice S[i] a S[i] + add .
- De lo contrario, actualice el valor de add a (S[i] + add – z) y luego configure S[i] a (a + add – 1) .
- Después de completar los pasos anteriores, imprima la string modificada S .
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 modify string by replacing // characters by the alphabet present at // distance equal to frequency of the string void addFrequencyToCharacter(string s) { // Stores frequency of characters int frequency[26] = { 0 }; // Stores length of the string int n = s.size(); // Traverse the given string S for (int i = 0; i < n; i++) { // Increment frequency of // current character by 1 frequency[s[i] - 'a'] += 1; } // Traverse the string for (int i = 0; i < n; i++) { // Store the value to be added // to the current character int add = frequency[s[i] - 'a'] % 26; // Check if after adding the // frequency, the character is // less than 'z' or not if (int(s[i]) + add <= int('z')) s[i] = char(int(s[i]) + add); // Otherwise, update the value of // add so that s[i] doesn't exceed 'z' else { add = (int(s[i]) + add) - (int('z')); s[i] = char(int('a') + add - 1); } } // Print the modified string cout << s; } // Driver Code int main() { string str = "geeks"; addFrequencyToCharacter(str); return 0; }
Java
// Java program for the above approach class GFG{ // Function to modify string by replacing // characters by the alphabet present at // distance equal to frequency of the string static void addFrequencyToCharacter(char[] s) { // Stores frequency of characters int frequency[] = new int[26]; // Stores length of the string int n = s.length; // Traverse the given string S for(int i = 0; i < n; i++) { // Increment frequency of // current character by 1 frequency[s[i] - 'a'] += 1; } // Traverse the string for(int i = 0; i < n; i++) { // Store the value to be added // to the current character int add = frequency[s[i] - 'a'] % 26; // Check if after adding the // frequency, the character is // less than 'z' or not if ((int)(s[i]) + add <= (int)('z')) s[i] = (char)((int)(s[i]) + add); // Otherwise, update the value of // add so that s[i] doesn't exceed 'z' else { add = ((int)(s[i]) + add) - ((int)('z')); s[i] = (char)((int)('a') + add - 1); } } // Print the modified string System.out.println(s); } // Driver Code public static void main(String[] args) { String str = "geeks"; addFrequencyToCharacter(str.toCharArray()); } } // This code is contributed by AnkThon
Python3
# Python3 program for the above approach # Function to modify string by replacing # characters by the alphabet present at # distance equal to frequency of the string def addFrequencyToCharacter(s): # Stores frequency of characters frequency = [0] * 26 # Stores length of the string n = len(s) # Traverse the given string S for i in range(n): # Increment frequency of # current character by 1 frequency[ord(s[i]) - ord('a')] += 1 # Traverse the string for i in range(n): # Store the value to be added # to the current character add = frequency[ord(s[i]) - ord('a')] % 26 # Check if after adding the # frequency, the character is # less than 'z' or not if (ord(s[i]) + add <= ord('z')): s[i] = chr(ord(s[i]) + add) # Otherwise, update the value of # add so that s[i] doesn't exceed 'z' else: add = (ord(s[i]) + add) - (ord('z')) s[i] = chr(ord('a') + add - 1) # Print the modified string print("".join(s)) # Driver Code if __name__ == '__main__': str = "geeks" addFrequencyToCharacter([i for i in str]) # This code is contributed by mohit kumar 29
C#
// C# program for the above approach using System; class GFG{ // Function to modify string by replacing // characters by the alphabet present at // distance equal to frequency of the string static void addFrequencyToCharacter(char[] s) { // Stores frequency of characters int[] frequency = new int[26]; // Stores length of the string int n = s.Length; // Traverse the given string S for(int i = 0; i < n; i++) { // Increment frequency of // current character by 1 frequency[s[i] - 'a'] += 1; } // Traverse the string for(int i = 0; i < n; i++) { // Store the value to be added // to the current character int add = frequency[s[i] - 'a'] % 26; // Check if after adding the // frequency, the character is // less than 'z' or not if ((int)(s[i]) + add <= (int)('z')) s[i] = (char)((int)(s[i]) + add); // Otherwise, update the value of // add so that s[i] doesn't exceed 'z' else { add = ((int)(s[i]) + add) - ((int)('z')); s[i] = (char)((int)('a') + add - 1); } } // Print the modified string Console.WriteLine(s); } // Driver Code public static void Main(string[] args) { string str = "geeks"; addFrequencyToCharacter(str.ToCharArray()); } } // This code is contributed by ukasp
Javascript
<script> // JavaScript program for the above approach // Function to modify string by replacing // characters by the alphabet present at // distance equal to frequency of the string function addFrequencyToCharacter(s) { // Stores frequency of characters var frequency = new Array(26).fill(0); // Stores length of the string var n = s.length; // Traverse the given string S for (var i = 0; i < n; i++) { // Increment frequency of // current character by 1 frequency[s[i].charCodeAt(0) - "a".charCodeAt(0)] += 1; } // Traverse the string for (var i = 0; i < n; i++) { // Store the value to be added // to the current character var add = frequency[s[i].charCodeAt(0) - "a".charCodeAt(0)] % 26; // Check if after adding the // frequency, the character is // less than 'z' or not if (s[i].charCodeAt(0) + add <= "z".charCodeAt(0)) s[i] = String.fromCharCode(s[i].charCodeAt(0) + add); // Otherwise, update the value of // add so that s[i] doesn't exceed 'z' else { add = s[i].charCodeAt(0) + add - "z".charCodeAt(0); s[i] = String.fromCharCode("a".charCodeAt(0) + add - 1); } } // Print the modified string document.write(s.join("") + "<br>"); } // Driver Code var str = "geeks"; addFrequencyToCharacter(str.split("")); </script>
hgglt
Complejidad temporal: O(N)
Espacio auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por coder_nero y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA