Dada la string str de longitud N , la tarea es obtener la string lexicográficamente más grande mediante un intercambio como máximo.
Nota: Es posible que los caracteres de intercambio no sean adyacentes.
Ejemplos:
Entrada: str = “string”
Salida: tsring
Explicación:
La string lexicográficamente más grande obtenida intercambiando st ring -> ts ring.Entrada: str = “zyxw”
Salida: zyxw
Explicación:
La string dada ya es lexicográficamente más grande
Enfoque:
Para resolver el problema mencionado anteriormente, la idea principal es utilizar Clasificación y calcular la string lexicográfica más grande posible para la string dada. Después de ordenar la string dada en orden descendente, busque el primer carácter no coincidente de la string dada y reemplácelo con la última aparición del carácter no coincidente en la string ordenada.
Ilustración:
str = “geeks”
String ordenada en orden descendente = “skgee”.
El primer personaje inigualable está en primer lugar. Este carácter debe intercambiarse con el carácter en esta posición en la string ordenada, lo que da como resultado la string lexicográficamente más grande. Al reemplazar la “g” por la “s”, la string obtenida es “seekg”, que es lexicográficamente la más grande después de un intercambio.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation to find the // lexicographically largest string // by atmost at most one swap #include <bits/stdc++.h> using namespace std; // Function to return the // lexicographically largest // string possible by swapping // at most one character string findLargest(string s) { int len = s.size(); // Stores last occurrence // of every character int loccur[26]; // Initialize with -1 for // every character memset(loccur, -1, sizeof(loccur)); for (int i = len - 1; i >= 0; --i) { // Keep updating the last // occurrence of each character int chI = s[i] - 'a'; // If a previously unvisited // character occurs if (loccur[chI] == -1) { loccur[chI] = i; } } // Stores the sorted string string sorted_s = s; sort(sorted_s.begin(), sorted_s.end(), greater<int>()); for (int i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // Character to replace int chI = sorted_s[i] - 'a'; // Find the last occurrence // of this character int last_occ = loccur[chI]; // Swap this with the last // occurrence swap(s[i], s[last_occ]); break; } } return s; } // Driver Program int main() { string s = "yrstvw"; cout << findLargest(s); return 0; }
Java
// Java implementation to find the // lexicographically largest string // by atmost at most one swap import java.util.*; import java.lang.*; class GFG{ // Function to return the // lexicographically largest // string possible by swapping // at most one character static String findLargest(StringBuilder s) { int len = s.length(); // Stores last occurrence // of every character int[] loccur = new int[26]; // Initialize with -1 for // every character Arrays.fill(loccur, -1); for(int i = len - 1; i >= 0; --i) { // Keep updating the last // occurrence of each character int chI = s.charAt(i) - 'a'; // If a previously unvisited // character occurs if (loccur[chI] == -1) { loccur[chI] = i; } } // Stores the sorted string char[] sorted_s = s.toString().toCharArray(); Arrays.sort(sorted_s); reverse(sorted_s); for(int i = 0; i < len; ++i) { if (s.charAt(i) != sorted_s[i]) { // Character to replace int chI = sorted_s[i] - 'a'; // Find the last occurrence // of this character int last_occ = loccur[chI]; // Swap this with the last // occurrence char tmp = s.charAt(i); s.setCharAt(i, s.charAt(last_occ)); s.setCharAt(last_occ, tmp); break; } } return s.toString(); } // Function to reverse array static void reverse(char a[]) { int i, n = a.length; for(i = 0; i < n / 2; i++) { char t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // Driver Code public static void main(String[] args) { StringBuilder s = new StringBuilder("yrstvw"); System.out.println(findLargest(s)); } } // This code is contributed by offbeat
Python3
# Python3 implementation to find the # lexicographically largest string # by atmost at most one swap # Function to return the # lexicographically largest # string possible by swapping # at most one character def findLargest(s): Len = len(s) # Stores last occurrence # of every character # Initialize with -1 for # every character loccur = [-1 for i in range(26)] for i in range(Len - 1, -1, -1): # Keep updating the last # occurrence of each character chI = ord(s[i]) - ord('a') # If a previously unvisited # character occurs if(loccur[chI] == -1): loccur[chI] = i # Stores the sorted string sorted_s = sorted(s, reverse = True) for i in range(Len): if(s[i] != sorted_s[i]): # Character to replace chI = (ord(sorted_s[i]) - ord('a')) # Find the last occurrence # of this character last_occ = loccur[chI] temp = list(s) # Swap this with the last # occurrence temp[i], temp[last_occ] = (temp[last_occ], temp[i]) s = "".join(temp) break return s # Driver code s = "yrstvw" print(findLargest(s)) # This code is contributed by avanitrachhadiya2155
C#
// C# implementation to find the // lexicographically largest string // by atmost at most one swap using System; using System.Collections.Generic; class GFG{ // Function to return the // lexicographically largest // string possible by swapping // at most one character static string findLargest(char[] s) { int len = s.Length; // Stores last occurrence // of every character int[] loccur = new int[26]; // Initialize with -1 for // every character Array.Fill(loccur, -1); for(int i = len - 1; i >= 0; --i) { // Keep updating the last // occurrence of each character int chI = s[i] - 'a'; // If a previously unvisited // character occurs if (loccur[chI] == -1) { loccur[chI] = i; } } // Stores the sorted string char[] sorted_s = (new string(s)).ToCharArray(); Array.Sort(sorted_s); Array.Reverse(sorted_s); for(int i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // Character to replace int chI = sorted_s[i] - 'a'; // Find the last occurrence // of this character int last_occ = loccur[chI]; // Swap this with the last // occurrence char temp = s[i]; s[i] = s[last_occ]; s[last_occ] = temp; break; } } return (new string(s)); } // Driver Code static void Main() { string str = "yrstvw"; char[] s = str.ToCharArray(); Console.WriteLine(findLargest(s)); } } // This code is contributed by divyesh072019
Javascript
<script> // Javascript implementation to find the // lexicographically largest string // by atmost at most one swap // Function to return the // lexicographically largest // string possible by swapping // at most one character function findLargest(s) { let len = s.length; // Stores last occurrence // of every character let loccur = new Array(26); // Initialize with -1 for // every character loccur.fill(-1); for(let i = len - 1; i >= 0; --i) { // Keep updating the last // occurrence of each character let chI = s[i].charCodeAt() - 'a'.charCodeAt(); // If a previously unvisited // character occurs if (loccur[chI] == -1) { loccur[chI] = i; } } // Stores the sorted string let sorted_s = s.join("").split(''); sorted_s.sort(); sorted_s.reverse(); for(let i = 0; i < len; ++i) { if (s[i] != sorted_s[i]) { // Character to replace let chI = sorted_s[i].charCodeAt() - 'a'.charCodeAt(); // Find the last occurrence // of this character let last_occ = loccur[chI]; // Swap this with the last // occurrence let temp = s[i]; s[i] = s[last_occ]; s[last_occ] = temp; break; } } return (s.join("")); } let str = "yrstvw"; let s = str.split(''); document.write(findLargest(s)); </script>
ywstvr
Publicación traducida automáticamente
Artículo escrito por chitrasingla2001 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA