Escriba código para encontrar el mínimo lexicográfico en una array circular, por ejemplo, para la array BCABDADAB, el mínimo lexicográfico es ABBCABDAD.
Fuente: prueba escrita de Google
Más ejemplos:
Input: GEEKSQUIZ Output: EEKSQUIZG Input: GFG Output: FGG Input: GEEKSFORGEEKS Output: EEKSFORGEEKSG
La siguiente es una solución simple. Deje que la string dada sea ‘str’
- Concatene ‘str’ consigo mismo y guárdelo en una string temporal, diga ‘concat’.
- Cree una array de strings para almacenar todas las rotaciones de ‘str’. Deje que la array sea ‘arr’.
- Encuentre todas las rotaciones de ‘str’ tomando substrings de ‘concat’ en el índice 0, 1, 2..n-1. Guarde estas rotaciones en arr[]
- Ordenar arr[] y devolver arr[0].
A continuación se muestra la implementación de la solución anterior.
C++
// A simple C++ program to find lexicographically minimum rotation // of a given string #include <iostream> #include <algorithm> using namespace std; // This functionr return lexicographically minimum // rotation of str string minLexRotation(string str) { // Find length of given string int n = str.length(); // Create an array of strings to store all rotations string arr[n]; // Create a concatenation of string with itself string concat = str + str; // One by one store all rotations of str in array. // A rotation is obtained by getting a substring of concat for (int i = 0; i < n; i++) arr[i] = concat.substr(i, n); // Sort all rotations sort(arr, arr+n); // Return the first rotation from the sorted array return arr[0]; } // Driver program to test above function int main() { cout << minLexRotation("GEEKSFORGEEKS") << endl; cout << minLexRotation("GEEKSQUIZ") << endl; cout << minLexRotation("BCABDADAB") << endl; }
Java
// A simple Java program to find // lexicographically minimum rotation // of a given String import java.util.*; class GFG { // This functionr return lexicographically // minimum rotation of str static String minLexRotation(String str) { // Find length of given String int n = str.length(); // Create an array of strings // to store all rotations String arr[] = new String[n]; // Create a concatenation of // String with itself String concat = str + str; // One by one store all rotations // of str in array. A rotation is // obtained by getting a substring of concat for (int i = 0; i < n; i++) { arr[i] = concat.substring(i, i + n); } // Sort all rotations Arrays.sort(arr); // Return the first rotation // from the sorted array return arr[0]; } // Driver code public static void main(String[] args) { System.out.println(minLexRotation("GEEKSFORGEEKS")); System.out.println(minLexRotation("GEEKSQUIZ")); System.out.println(minLexRotation("BCABDADAB")); } } // This code is contributed by 29AjayKumar
Python3
# A simple Python3 program to find lexicographically # minimum rotation of a given string # This function return lexicographically minimum # rotation of str def minLexRotation(str_) : # Find length of given string n = len(str_) # Create an array of strings to store all rotations arr = [0] * n # Create a concatenation of string with itself concat = str_ + str_ # One by one store all rotations of str in array. # A rotation is obtained by getting a substring of concat for i in range(n) : arr[i] = concat[i : n + i] # Sort all rotations arr.sort() # Return the first rotation from the sorted array return arr[0] # Driver Code print(minLexRotation("GEEKSFORGEEKS")) print(minLexRotation("GEEKSQUIZ")) print(minLexRotation("BCABDADAB")) # This code is contributed by divyamohan123
C#
// A simple C# program to find // lexicographically minimum rotation // of a given String using System; class GFG { // This functionr return lexicographically // minimum rotation of str static String minLexRotation(String str) { // Find length of given String int n = str.Length; // Create an array of strings // to store all rotations String []arr = new String[n]; // Create a concatenation of // String with itself String concat = str + str; // One by one store all rotations // of str in array. A rotation is // obtained by getting a substring of concat for (int i = 0; i < n; i++) { arr[i] = concat.Substring(i, n); } // Sort all rotations Array.Sort(arr); // Return the first rotation // from the sorted array return arr[0]; } // Driver code public static void Main(String[] args) { Console.WriteLine(minLexRotation("GEEKSFORGEEKS")); Console.WriteLine(minLexRotation("GEEKSQUIZ")); Console.WriteLine(minLexRotation("BCABDADAB")); } } // This code is contributed by Rajput-Ji
Javascript
<script> // A simple Javascript program to find // lexicographically minimum rotation // of a given String // This functionr return lexicographically // minimum rotation of str function minLexRotation(str) { // Find length of given String let n = str.length; // Create an array of strings // to store all rotations let arr = new Array(n); // Create a concatenation of // String with itself let concat = str + str; // One by one store all rotations // of str in array. A rotation is // obtained by getting a substring of concat for(let i = 0; i < n; i++) { arr[i] = concat.substring(i, i + n); } // Sort all rotations arr.sort(); // Return the first rotation // from the sorted array return arr[0]; } // Driver code document.write(minLexRotation("GEEKSFORGEEKS") + "</br>"); document.write(minLexRotation("GEEKSQUIZ") + "</br>"); document.write(minLexRotation("BCABDADAB") + "</br>"); // This code is contributed by divyeshrabadiya07 </script>
EEKSFORGEEKSG EEKSQUIZG ABBCABDAD
Secuencia rotada lexicográficamente más pequeña | conjunto 2
La complejidad temporal de la solución anterior es O(n 2 Logn) bajo el supuesto de que hemos utilizado un algoritmo de clasificación O(nLogn).
Espacio Auxiliar: O(n)
Este problema se puede resolver usando métodos más eficientes como el Algoritmo de Booth que resuelve el problema en tiempo O(n). Pronto cubriremos estos métodos como publicaciones separadas.
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA