Reorganice los caracteres de la string de modo que no haya dos caracteres adyacentes que sean alfabetos ingleses consecutivos

La string dada str de tamaño N consta de alfabetos ingleses en minúsculas. La tarea es encontrar la disposición de los caracteres de la string de modo que no haya dos caracteres adyacentes vecinos en los alfabetos ingleses. En caso de múltiples respuestas imprima cualquiera de ellas. Si tal arreglo no es posible, imprima -1.
Ejemplos: 
 

Entrada: str = “aabcd” 
Salida: bdaac 
No hay dos caracteres adyacentes que sean vecinos en los alfabetos ingleses.
Entrada: str = “aab” 
Salida: -1 
 

Enfoque: Atraviese la string y almacene todos los caracteres impares en una string, los caracteres pares e impares en otra string , es decir, cada dos caracteres consecutivos en ambas strings tendrán una diferencia absoluta en los valores ASCII de al menos 2. Luego ordene ambos instrumentos de cuerda. Ahora, si alguna de las concatenaciones (par + impar) o (impar + par) es válida, imprima el arreglo válido; de lo contrario, no es posible reorganizar la string de la manera requerida.
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 true if the
// current arrangement is valid
bool check(string s)
{
    for (int i = 0; i + 1 < s.size(); ++i)
        if (abs(s[i] - s[i + 1]) == 1)
            return false;
    return true;
}
 
// Function to rearrange the characters of
// the string such that no two neighbours
// in the English alphabets appear together
void Rearrange(string str)
{
    // To store the odd and the
    // even positioned characters
    string odd = "", even = "";
 
    // Traverse through the array
    for (int i = 0; i < str.size(); ++i) {
        if (str[i] % 2 == 0)
            even += str[i];
        else
            odd += str[i];
    }
 
    // Sort both the strings
    sort(odd.begin(), odd.end());
    sort(even.begin(), even.end());
 
    // Check possibilities
    if (check(odd + even))
        cout << odd + even;
    else if (check(even + odd))
        cout << even + odd;
    else
        cout << -1;
}
 
// Driver code
int main()
{
    string str = "aabcd";
 
    Rearrange(str);
 
    return 0;
}

Java

// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
    // Function that returns true if the
    // current arrangement is valid
    static boolean check(String s)
    {
        for (int i = 0; i + 1 < s.length(); ++i)
        {
            if (Math.abs(s.charAt(i) -
                         s.charAt(i + 1)) == 1)
            {
                return false;
            }
        }
        return true;
    }
 
    // Function to rearrange the characters of
    // the string such that no two neighbours
    // in the English alphabets appear together
    static void Rearrange(String str)
    {
         
        // To store the odd and the
        // even positioned characters
        String odd = "", even = "";
 
        // Traverse through the array
        for (int i = 0; i < str.length(); ++i)
        {
            if (str.charAt(i) % 2 == 0)
            {
                even += str.charAt(i);
            }
            else
            {
                odd += str.charAt(i);
            }
        }
 
        // Sort both the strings
        odd = sort(odd);
        even = sort(even);
 
        // Check possibilities
        if (check(odd + even))
        {
            System.out.print(odd + even);
        }
        else if (check(even + odd))
        {
            System.out.print(even + odd);
        }
        else
        {
            System.out.print(-1);
        }
    }
     
    // Method to sort a string alphabetically
    public static String sort(String inputString)
    {
        // convert input string to char array
        char tempArray[] = inputString.toCharArray();
 
        // sort tempArray
        Arrays.sort(tempArray);
 
        // return new sorted string
        return new String(tempArray);
    }
     
    // Driver code
    public static void main(String[] args)
    {
        String str = "aabcd";
 
        Rearrange(str);
    }
}
 
// This code is contributed by 29AjayKumar

Python3

# Python3 implementation of the approach
 
# Function that returns true if the
# current arrangement is valid
def check(s):
 
    for i in range(len(s) - 1):
        if (abs(ord(s[i]) -
                ord(s[i + 1])) == 1):
            return False
    return True
 
# Function to rearrange the characters
# of the such that no two neighbours
# in the English alphabets appear together
def Rearrange(Str):
 
    # To store the odd and the
    # even positioned characters
    odd, even = "",""
 
    # Traverse through the array
    for i in range(len(Str)):
        if (ord(Str[i]) % 2 == 0):
            even += Str[i]
        else:
            odd += Str[i]
 
    # Sort both the Strings
    odd = sorted(odd)
    even = sorted(even)
 
    # Check possibilities
    if (check(odd + even)):
        print("".join(odd + even))
    elif (check(even + odd)):
        print("".join(even + odd))
    else:
        print(-1)
 
# Driver code
Str = "aabcd"
 
Rearrange(Str)
 
# This code is contributed
# by Mohit Kumar

C#

// C# implementation of the approach
using System;
     
class GFG
{
 
    // Function that returns true if the
    // current arrangement is valid
    static Boolean check(String s)
    {
        for (int i = 0; i + 1 < s.Length; ++i)
        {
            if (Math.Abs(s[i] -
                         s[i + 1]) == 1)
            {
                return false;
            }
        }
        return true;
    }
 
    // Function to rearrange the characters of
    // the string such that no two neighbours
    // in the English alphabets appear together
    static void Rearrange(String str)
    {
         
        // To store the odd and the
        // even positioned characters
        String odd = "", even = "";
 
        // Traverse through the array
        for (int i = 0; i < str.Length; ++i)
        {
            if (str[i] % 2 == 0)
            {
                even += str[i];
            }
            else
            {
                odd += str[i];
            }
        }
 
        // Sort both the strings
        odd = sort(odd);
        even = sort(even);
 
        // Check possibilities
        if (check(odd + even))
        {
            Console.Write(odd + even);
        }
        else if (check(even + odd))
        {
            Console.Write(even + odd);
        }
        else
        {
            Console.Write(-1);
        }
    }
     
    // Method to sort a string alphabetically
    public static String sort(String inputString)
    {
        // convert input string to char array
        char []tempArray = inputString.ToCharArray();
 
        // sort tempArray
        Array.Sort(tempArray);
 
        // return new sorted string
        return new String(tempArray);
    }
     
    // Driver code
    public static void Main(String[] args)
    {
        String str = "aabcd";
 
        Rearrange(str);
    }
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
 
      // JavaScript implementation of the approach
       
      // Function that returns true if the
      // current arrangement is valid
      function check(s) {
        for (var i = 0; i + 1 < s.length; ++i)
        {
          if (Math.abs(s[i].charCodeAt(0) -
          s[i + 1].charCodeAt(0)) === 1)
          {
            return false;
          }
        }
        return true;
      }
 
      // Function to rearrange the characters of
      // the string such that no two neighbours
      // in the English alphabets appear together
      function Rearrange(str) {
        // To store the odd and the
        // even positioned characters
        var odd = "",
          even = "";
 
        // Traverse through the array
        for (var i = 0; i < str.length; ++i) {
          if (str[i].charCodeAt(0) % 2 === 0) {
            even += str[i];
          } else {
            odd += str[i];
          }
        }
 
        // Sort both the strings
        odd.split("").sort((a, b) => a - b);
        even.split("").sort((a, b) => a - b);
 
        // Check possibilities
        if (check(odd + even)) {
          document.write(odd + even);
        } else if (check(even + odd)) {
          document.write(even + odd);
        } else {
          document.write(-1);
        }
      }
 
      // Driver code
      var str = "aabcd";
      Rearrange(str);
       
</script>
Producción: 

bdaac

 

Complejidad de tiempo: Onlogn)

Espacio Auxiliar: O(n)

Publicación traducida automáticamente

Artículo escrito por pawan_asipu y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *