Dada una array de strings de palabras [] y el orden secuencial de los alfabetos, nuestra tarea es ordenar la array de acuerdo con el orden dado. Suponga que el diccionario y las palabras solo contienen alfabetos en minúsculas.
Ejemplos:
Entrada: palabras = {“hola”, “geeksforgeeks”}, orden = “hlabcdefgijkmnopqrstuvwxyz”
Salida: “hola”, “geeksforgeeks”
Explicación:
De acuerdo con el orden dado, ‘h’ aparece antes de ‘g’ y, por lo tanto, se considera que las palabras ser ordenadoEntrada: palabras = {“palabra”, “mundo”, “fila”}, orden = “mundoabcefghijkmnpqstuvxyz”
Salida: “mundo”, “palabra”, “fila”
Explicación:
Según el orden dado, ‘l’ aparece antes de ‘d ‘ por lo tanto, las palabras «mundo» se mantendrán primero.
Enfoque: para resolver el problema mencionado anteriormente, debemos mantener la prioridad de cada personaje en el orden dado. Para hacer eso, use Map Data Structure .
- Iterar en el orden dado y establecer la prioridad de un carácter en su valor de índice.
- Use una función de comparación personalizada para ordenar la array.
- En la función de comparación, itere a través de la palabra de tamaño mínimo entre las dos palabras e intente encontrar el primer carácter diferente, la palabra con el carácter de menor valor de prioridad será la palabra más pequeña.
- Si las palabras tienen el mismo prefijo, entonces la palabra de menor tamaño es la palabra más pequeña.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to sort an array // of strings based on the given order #include <bits/stdc++.h> using namespace std; // For storing priority of each character unordered_map<char, int> mp; // Custom comparator function for sort bool comp(string& a, string& b) { // Loop through the minimum size // between two words for (int i = 0; i < min(a.size(), b.size()); i++) { // Check if the characters // at position i are different, // then the word containing lower // valued character is smaller if (mp[a[i]] != mp[b[i]]) return mp[a[i]] < mp[b[i]]; } /* When loop breaks without returning, it means the prefix of both words were same till the execution of the loop. Now, the word with the smaller size will occur before in sorted order */ return (a.size() < b.size()); } // Function to print the // new sorted array of strings void printSorted(vector<string> words, string order) { // Mapping each character // to its occurrence position for (int i = 0; i < order.size(); i++) mp[order[i]] = i; // Sorting with custom sort function sort(words.begin(), words.end(), comp); // Printing the sorted order of words for (auto x : words) cout << x << " "; } // Driver code int main() { vector<string> words = { "word", "world", "row" }; string order = { "worldabcefghijkmnpqstuvxyz" }; printSorted(words, order); return 0; }
Python3
# Python3 program to sort an array # of strings based on the given order from functools import cmp_to_key # For storing priority of each character mp = {} # Custom comparator function for sort def comp(a, b): # Loop through the minimum size # between two words for i in range( min(len(a), len(b))): # Check if the characters # at position i are different, # then the word containing lower # valued character is smaller if (mp[a[i]] != mp[b[i]]): if mp[a[i]] < mp[b[i]]: return -1 else: return 1 '''When loop breaks without returning, it means the prefix of both words were same till the execution of the loop. Now, the word with the smaller size will occur before in sorted order''' if (len(a) < len(b)): return -1 else: return 1 # Function to print the # new sorted array of strings def printSorted(words, order): # Mapping each character # to its occurrence position for i in range(len(order)): mp[order[i]] = i # Sorting with custom sort function words = sorted(words, key = cmp_to_key(comp)) # Printing the sorted order of words for x in words: print(x, end = " ") # Driver code words = [ "word", "world", "row" ] order = "worldabcefghijkmnpqstuvxyz" printSorted(words, order) # This code is contributed by Shivani
Javascript
<script> // JavaScript program to sort an array // of strings based on the given order // For storing priority of each character let mp = new Map(); // Custom comparator function for sort function comp(a, b) { // Loop through the minimum size // between two words for (let i = 0; i < Math.min(a.length, b.length);i++) { // Check if the characters // at position i are different, // then the word containing lower // valued character is smaller if (mp.get(a[i]) != mp.get(b[i])) return mp.get(b[i]) - mp.get(a[i]); } /* When loop breaks without returning, it means the prefix of both words were same till the execution of the loop. Now, the word with the smaller size will occur before in sorted order */ return (b.length - a.length); } // Function to print the // new sorted array of strings function printSorted(words,order) { // Mapping each character // to its occurrence position for (let i = 0; i < order.length; i++) mp.set(order[i],i); // Sorting with custom sort function words.sort(comp); // Printing the sorted order of words for (let x of words) document.write(x +" "); } // Driver code let words = ["word", "world", "row" ]; let order = ["worldabcefghijkmnpqstuvxyz" ]; printSorted(words, order); // This code is contributed by shinjanpatra </script>
world word row