Dada una string alfanumérica str , la tarea es ordenar la string de tal manera que si una posición está ocupada por un alfabeto, debe ser ocupada por un alfabeto después de la clasificación y si está ocupada por un número, debe ser ocupada por un número después de la clasificación. .
Ejemplos:
Entrada: str = “geeks12for32geeks”
Salida: eeeef12ggk23korss
Entrada: str = “d4c3b2a1”
Salida: a1b2c3d4
Enfoque: convertiremos la string en una array de caracteres y luego ordenaremos la array de caracteres c[] . Después de ordenar la array de caracteres, los caracteres numéricos ocuparán los índices iniciales de la array y los alfabetos ocuparán la parte restante de la array.
La mitad numérica se ordenará y la parte alfabética también se ordenará. Mantendremos dos índices, uno en el índice inicial de la parte del alfabeto al_c y otro en el índice inicial de la parte numérica nu_c , ahora verificaremos la string original y si una posición estaba ocupada por un alfabeto, la reemplazaremos con c[ al_c] e incrementamos al_c , de lo contrario lo reemplazaremos con c[nu_c] e incrementamosnu_c .
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function that returns the string s // in sorted form such that the // positions of alphabets and numeric // digits remain unchanged string sort(string s) { char c[s.length() + 1]; // String to character array strcpy(c, s.c_str()); // Sort the array sort(c, c + s.length()); // Count of alphabets and numbers int al_c = 0, nu_c = 0; // Get the index from where the // alphabets start while (c[al_c] < 97) al_c++; // Now replace the string with sorted string for (int i = 0; i < s.length(); i++) { // If the position was occupied by an // alphabet then replace it with alphabet if (s[i] < 97) s[i] = c[nu_c++]; // Else replace it with a number else s[i] = c[al_c++]; } // Return the sorted string return s; } // Driver code int main() { string s = "d4c3b2a1"; cout << sort(s); return 0; }
Java
// A Java implementation of the approach import java.util.*; class GFG { // Function that returns the string s // in sorted form such that the // positions of alphabets and numeric // digits remain unchanged static String sort(String s) { char []c = new char[s.length() + 1]; // String to character array c = s.toCharArray(); // Sort the array Arrays.sort(c); // Count of alphabets and numbers int al_c = 0, nu_c = 0; // Get the index from where the // alphabets start while (c[al_c] < 97) al_c++; // Now replace the string with sorted string for (int i = 0; i < s.length(); i++) { // If the position was occupied by an // alphabet then replace it with alphabet if (s.charAt(i) < 97) s = s.substring(0,i)+ c[nu_c++]+s.substring(i+1); // Else replace it with a number else s = s.substring(0,i)+ c[al_c++]+s.substring(i+1); } // Return the sorted string return s; } // Driver code public static void main(String[] args) { String s = "d4c3b2a1"; System.out.println(sort(s)); } } /* This code contributed by PrinciRaj1992 */
Python3
# Python3 implementation of the approach # Function that returns the string s # in sorted form such that the # positions of alphabets and numeric # digits remain unchanged def sort(s): # String to character array c, s = list(s), list(s) # Sort the array c.sort() # Count of alphabets and numbers al_c = 0 nu_c = 0 # Get the index from where the # alphabets start while ord(c[al_c]) < 97: al_c += 1 # Now replace the string with sorted string for i in range(len(s)): # If the position was occupied by an # alphabet then replace it with alphabet if s[i] < 'a': s[i] = c[nu_c] nu_c += 1 # Else replace it with a number else: s[i] = c[al_c] al_c += 1 # Return the sorted string return ''.join(s) # Driver Code if __name__ == "__main__": s = "d4c3b2a1" print(sort(s)) # This code is contributed by # sanjeev2552
C#
// C# implementation of the approach using System; class GFG { // Function that returns the string s // in sorted form such that the // positions of alphabets and numeric // digits remain unchanged static string sort(string s) { char []c = new char[s.Length + 1]; // String to character array c = s.ToCharArray(); // Sort the array Array.Sort(c); // Count of alphabets and numbers int al_c = 0, nu_c = 0; // Get the index from where the // alphabets start while (c[al_c] < 97) al_c++; // Now replace the string with sorted string for (int i = 0; i < s.Length; i++) { // If the position was occupied by an // alphabet then replace it with alphabet if (s[i] < 97) s = s.Substring(0,i)+ c[nu_c++]+s.Substring(i+1); // Else replace it with a number else s = s.Substring(0,i)+ c[al_c++]+s.Substring(i+1); } // Return the sorted string return s; } // Driver code public static void Main() { string s = "d4c3b2a1"; Console.WriteLine(sort(s)); } } /* This code contributed by AnkitRai01 */
Javascript
<script> // Javascript implementation of the approach // Function that returns the string s // in sorted form such that the // positions of alphabets and numeric // digits remain unchanged function sort(s) { var c = s.split(''); c.sort(); // Count of alphabets and numbers var al_c = 0, nu_c = 0; // Get the index from where the // alphabets start while (c[al_c].charCodeAt(0) < 97) al_c++; // Now replace the string with sorted string for (var i = 0; i < s.length; i++) { // If the position was occupied by an // alphabet then replace it with alphabet if (s[i].charCodeAt(0) < 97) s = s.substring(0,i)+ c[nu_c++]+s.substring(i+1); // Else replace it with a number else s = s.substring(0,i)+ c[al_c++]+s.substring(i+1); } // Return the sorted string return s; } // Driver code var s = "d4c3b2a1"; document.write( sort(s)); // This code is contributed by rutvik_56. </script>
a1b2c3d4
Complejidad de tiempo: O(N * log(N)) donde N es la longitud de la string.
Publicación traducida automáticamente
Artículo escrito por andrew1234 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA