Dada la string str que contiene letras en minúsculas (a – z). La tarea es imprimir la string después de reorganizar algunos caracteres de modo que la string se vuelva no palindrómica. Si es imposible hacer que la string no sea palíndromo, imprima -1 .
Ejemplos:
Entrada: str = “abba”
Salida: aabb
Entrada: str = “zzz”
Salida: -1
Enfoque: si todos los caracteres de la string son iguales, no importa cómo los reorganice, la string seguirá siendo la misma y será palindrómica. Ahora, si existe un arreglo no palindrómico, la mejor manera de reorganizar los caracteres es ordenar la string que formará un segmento continuo de los mismos caracteres y nunca será palindrómico. Para reducir el tiempo necesario para clasificar la string, podemos almacenar las frecuencias de los 26 caracteres e imprimirlos de forma ordenada.
A continuación se muestra la implementación del enfoque anterior:
C++
// CPP Program to rearrange letters of string // to find a non-palindromic string if it exists #include <bits/stdc++.h> using namespace std; // Function to print the non-palindromic string // if it exists, otherwise prints -1 void findNonPalinString(string s) { int freq[26] = { 0 }, flag = 0; for (int i = 0; i < s.size(); i++) { // If all characters are not // same, set flag to 1 if (s[i] != s[0]) flag = 1; // Update frequency of the current character freq[s[i] - 'a']++; } // If all characters are same if (!flag) cout << "-1"; else { // Print characters in sorted manner for (int i = 0; i < 26; i++) for (int j = 0; j < freq[i]; j++) cout << char('a' + i); } } // Driver Code int main() { string s = "abba"; findNonPalinString(s); return 0; }
Java
// Java Program to rearrange letters of string // to find a non-palindromic string if it exists class GfG { // Function to print the non-palindromic string // if it exists, otherwise prints -1 static void findNonPalinString(char s[]) { int freq[] = new int[26]; int flag = 0; for (int i = 0; i < s.length; i++) { // If all characters are not // same, set flag to 1 if (s[i] != s[0]) flag = 1; // Update frequency of // the current character freq[s[i] - 'a']++; } // If all characters are same if (flag == 0) System.out.println("-1"); else { // Print characters in sorted manner for (int i = 0; i < 26; i++) for (int j = 0; j < freq[i]; j++) System.out.print((char)('a' + i)); } } // Driver Code public static void main(String[] args) { String s = "abba"; findNonPalinString(s.toCharArray()); } } // This code is contributed by // Prerna Saini.
Python3
# Python3 Program to rearrange letters of string # to find a non-palindromic string if it exists # Function to print the non-palindromic string # if it exists, otherwise prints -1 def findNonPalinString(s): freq = [0] * (26) flag = 0 for i in range(0, len(s)): # If all characters are not same, # set flag to 1 if s[i] != s[0]: flag = 1 # Update frequency of the current # character freq[ord(s[i]) - ord('a')] += 1 # If all characters are same if not flag: print("-1") else: # Print characters in sorted manner for i in range(0, 26): for j in range(0, freq[i]): print(chr(ord('a') + i), end = "") # Driver Code if __name__ == "__main__": s = "abba" findNonPalinString(s) # This code is contributed by # Rituraj Jain
C#
// C# Program to rearrange letters // of string to find a non-palindromic // string if it exists using System; class GfG { // Function to print the // non-palindromic string // if it exists, otherwise // prints -1 static void findNonPalinString(char []s) { int []freq = new int[26]; int flag = 0; for (int i = 0; i < s.Length; i++) { // If all characters are not // same, set flag to 1 if (s[i] != s[0]) flag = 1; // Update frequency of // the current character freq[s[i] - 'a']++; } // If all characters are same if (flag == 0) Console.WriteLine("-1"); else { // Print characters in sorted manner for (int i = 0; i < 26; i++) for (int j = 0; j < freq[i]; j++) Console.Write((char)('a' + i)); } } // Driver Code public static void Main() { string s = "abba"; findNonPalinString(s.ToCharArray()); } } // This code is contributed by Ryuga
Javascript
<script> // JavaScript Program to rearrange letters of string // to find a non-palindromic string if it exists // Function to print the non-palindromic string // if it exists, otherwise prints -1 function findNonPalinString(s) { var freq = Array.from({length: 26}, (_, i) => 0); var flag = 0; for (var i = 0; i < s.length; i++) { // If all characters are not // same, set flag to 1 if (s[i] != s[0]) flag = 1; // Update frequency of // the current character freq[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; } // If all characters are same if (flag == 0) document.write("-1"); else { // Print characters in sorted manner for (var i = 0; i < 26; i++) for (var j = 0; j < freq[i]; j++) document.write(String.fromCharCode ('a'.charCodeAt(0) + i)); } } // Driver Code var s = "abba"; findNonPalinString(s.split('')); // This code contributed by shikhasingrajput </script>
aabb
Complejidad temporal: O(N)
Espacio auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por Nishant Tanwar y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA