Número mínimo de caracteres a reemplazar para hacer una string dada Palindrome

Dada la string str , la tarea es encontrar el número mínimo de caracteres que se reemplazarán para hacer un palíndromo de string dado. Reemplazar un carácter significa reemplazarlo con cualquier carácter individual en la misma posición. No se nos permite eliminar o agregar ningún carácter. 

Si hay múltiples respuestas, imprima la string lexicográficamente más pequeña.

Ejemplos:  

Input: str = "geeks"
Output: 2
geeks can be converted to geeeg to make it palindrome
by replacing minimum characters.

Input: str = "ameba"
Output: 1
We can get "abeba" or "amema" with only 1 change. 
Among those two, "abeba" is lexicographically smallest. 

Enfoque: Ejecute un bucle desde 0 hasta (longitud)/2-1 y verifique si un carácter en el i-ésimo índice, es decir, s[i]!=s[longitud-i-1], luego reemplazaremos el alfabéticamente más grande carácter con el que es alfabéticamente menor entre ellos y continuar el mismo proceso hasta recorrer todos los elementos.

A continuación se muestra la implementación del enfoque anterior:  

C++

// C++ Implementation of the above approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to find the minimum number
// character change required
  
void change(string s)
{
 
    // Finding the length of the string
    int n = s.length();
 
    // To store the number of replacement operations
    int cc = 0;
 
    for(int i=0;i<n/2;i++)
    {
 
        // If the characters at location
        // i and n-i-1 are same then
        // no change is required
        if(s[i]== s[n-i-1])
            continue;
 
        // Counting one change operation
        cc+= 1;
 
        // Changing the character with higher
        // ascii value with lower ascii value
        if(s[i]<s[n-i-1])
            s[n-i-1]= s[i] ;
        else
            s[i]= s[n-i-1] ;
    }
    printf("Minimum characters to be replaced = %d\n", (cc)) ;
    cout<<s<<endl;
}
// Driver code
int main()
{
string s = "geeks";
change((s));
return 0;
}
//contributed by Arnab Kundu

Java

// Java Implementation of the above approach
import java.util.*;
 
class GFG
{
 
// Function to find the minimum number
// character change required
static void change(String s)
{
 
    // Finding the length of the string
    int n = s.length();
 
    // To store the number of replacement operations
    int cc = 0;
 
    for(int i = 0; i < n/2; i++)
    {
 
        // If the characters at location
        // i and n-i-1 are same then
        // no change is required
        if(s.charAt(i) == s.charAt(n - i - 1))
            continue;
 
        // Counting one change operation
        cc += 1;
 
        // Changing the character with higher
        // ascii value with lower ascii value
        if(s.charAt(i) < s.charAt(n - i - 1))
            s = s.replace(s.charAt(n - i - 1),s.charAt(i));
        else
            s = s.replace(s.charAt(n-1),s.charAt(n - i - 1));
    }
    System.out.println("Minimum characters to be replaced = "+(cc)) ;
    System.out.println(s);
}
 
// Driver code
public static void main(String args[])
{
    String s = "geeks";
    change((s));
 
}
}
 
// This code is contributed by
// Nikhil Gupta

Python

# Python Implementation of the above approach
 
# Function to find the minimum number
# character change required
import math as ma
def change(s):
 
    # Finding the length of the string
    n = len(s)
 
    # To store the number of replacement operations
    cc = 0
 
    for i in range(n//2):
 
        # If the characters at location
        # i and n-i-1 are same then
        # no change is required
        if(s[i]== s[n-i-1]):
            continue
 
        # Counting one change operation
        cc+= 1
 
        # Changing the character with higher
        # ascii value with lower ascii value
        if(s[i]<s[n-i-1]):
            s[n-i-1]= s[i]
        else:
            s[i]= s[n-i-1]
 
    print("Minimum characters to be replaced = ", str(cc))
    print(*s, sep ="")
     
# Driver code
s = "geeks"
change(list(s))

C#

// C# Implementation of the above approach
using System;
     
class GFG
{
 
// Function to find the minimum number
// character change required
static void change(String s)
{
 
    // Finding the length of the string
    int n = s.Length;
 
    // To store the number of
    //replacement operations
    int cc = 0;
 
    for(int i = 0; i < n / 2; i++)
    {
 
        // If the characters at location
        // i and n-i-1 are same then
        // no change is required
        if(s[i] == s[n - i - 1])
            continue;
 
        // Counting one change operation
        cc += 1;
 
        // Changing the character with higher
        // ascii value with lower ascii value
        if(s[i] < s[n - i - 1])
            s = s.Replace(s[n - i - 1], s[i]);
        else
            s = s.Replace(s[n], s[n - i - 1]);
    }
    Console.WriteLine("Minimum characters " +
                      "to be replaced = " + (cc));
    Console.WriteLine(s);
}
 
// Driver code
public static void Main(String []args)
{
    String s = "geeks";
    change((s));
}
}
 
// This code contributed by Rajput-Ji

PHP

<?php
// PHP Implementation of the above approach
 
// Function to find the minimum number
// character change required
   
function change($s)
{
  
    // Finding the length of the string
    $n = strlen($s);
  
    // To store the number of replacement operations
    $cc = 0;
  
    for($i=0;$i<$n/2;$i++)
    {
  
        // If the characters at location
        // i and n-i-1 are same then
        // no change is required
        if($s[$i]== $s[$n-$i-1])
            continue;
  
        // Counting one change operation
        $cc+= 1;
  
        // Changing the character with higher
        // ascii value with lower ascii value
        if($s[$i]<$s[$n-$i-1])
            $s[$n-$i-1]= $s[$i] ;
        else
            $s[$i]= $s[$n-$i-1] ;
    }
    echo "Minimum characters to be replaced = ". $cc."\n" ;
    echo $s."\n";
}
// Driver code
 
$s = "geeks";
change(($s));
return 0;
?>

Javascript

<script>
 
// Javascript Implementation of the above approach
 
// Function to find the minimum number
// character change required
  
function change(s)
{
 
    // Finding the length of the string
    var n = s.length;
 
    // To store the number of replacement operations
    var cc = 0;
 
    for(var i=0;i<n/2;i++)
    {
 
        // If the characters at location
        // i and n-i-1 are same then
        // no change is required
        if(s[i]== s[n-i-1])
            continue;
 
        // Counting one change operation
        cc+= 1;
 
        // Changing the character with higher
        // ascii value with lower ascii value
        if(s[i]<s[n-i-1])
            s[n-i-1]= s[i] ;
        else
            s[i]= s[n-i-1] ;
    }
    document.write("Minimum characters to be replaced = " + (cc)+"<br>");
    document.write(s.join('') + "<br>");
}
 
// Driver code
var s = "geeks".split('');
change((s));
 
</script>
Producción: 

Minimum characters to be replaced =  2
geeeg

 

Publicación traducida automáticamente

Artículo escrito por indrajit1 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 *