Minimum cost to convert string into palindrome - GeeksforGeeks

21 May, 2021
Convert string S into a palindrome string. You can only replace a character with any other character. When you replace character ‘a’ with any other character, it costs 1 unit, similarly for ‘b’ it is 2 units ..... and for ‘z’, it is 26 units. Find the minimum cost required to convert string S into palindrome string.Examples :  
Input : abcdef
Output : 6
Explanation: replace 'a', 'b' and 
'c' => cost= 1 + 2 + 3 = 6 

Input : aba
Output : 0
 
The idea is to start comparing from the two ends of string. Let i be initialized as 0 index and j initialized as length – 1. If characters at two indices are not same, a cost will apply. To make the cost minimum replace the character which is smaller. Then increment i by 1 and decrement j by 1. Iterate till i less than j.  
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find minimum cost to make// a palindrome.#include <bits/stdc++.h>using namespace std; // Function to return costint cost(string str){    // length of string    int len = str.length();              // Iterate from  both sides of string.    // If not equal, a cost will be there    int res = 0;    for (int i=0, j=len-1; i < j; i++, j--)                if (str[i] != str[j])            res += min(str[i], str[j]) - 'a' + 1;                return res;} // Driver codeint main(){    string str = "abcdef";    cout << cost(str) << endl;    return 0;}
// Java program to find minimum cost to make// a palindrome.import java.io.*; class GFG{    // Function to return cost    static int cost(String str)    {        // length of string        int len = str.length();                 // Iterate from both sides of string.        // If not equal, a cost will be there        int res = 0;        for (int i = 0, j = len - 1; i < j; i++, j--)                if (str.charAt(i) != str.charAt(j))                res += Math.min(str.charAt(i), str.charAt(j))                                - 'a' + 1;                     return res;    }         // Driver code    public static void main (String[] args)    {        String str = "abcdef";        System.out.println(cost(str));    }} // This code is contributed by vt_m.
# python program to find minimum# cost to make a palindrome. # Function to return costdef cost(st):         # length of string    l = len(st)             # Iterate from both sides    # of string. If not equal,    # a cost will be there    res = 0    j = l - 1    i = 0    while(i < j):                if (st[i] != st[j]):            res += (min(ord(st[i]),                    ord(st[j])) -                     ord('a') + 1)                     i = i + 1        j = j - 1             return res # Driver codest = "abcdef";print(cost(st)) # This code is contributed by# Sam007
// C# program to find minimum cost// to make a palindrome.using System; class GFG{         // Function to return cost    static int cost(String str)    {        // length of string        int len = str.Length;                 // Iterate from both sides of string.        // If not equal, a cost will be there        int res = 0;        for (int i = 0, j = len - 1; i < j; i++, j--)                if (str[i] != str[j])                res += Math.Min(str[i], str[j])                                - 'a' + 1;                 return res;    }         // Driver code    public static void Main ()    {        string str = "abcdef";        Console.WriteLine(cost(str));    }} // This code is contributed by vt_m.
<?php// PHP program to find minimum// cost to make a palindrome. // Function to return costfunction cost($str){    // length of string    $len = strlen($str);             // Iterate from both sides    // of string. If not equal,    // a cost will be there    $res = 0;    for ($i = 0, $j = $len - 1;                $i < $j; $i++, $j--)                if ($str[$i] != $str[$j])            $res += (min(ord($str[$i]),                       ord($str[$j])) -                       ord('a') + 1 );             return $res;} // Driver code$str = "abcdef";echo cost($str); // This code is contributed by Sam007?>
<script>    // Javascript program to find minimum cost    // to make a palindrome.         // Function to return cost    function cost(str)    {        // length of string        let len = str.length;                   // Iterate from both sides of string.        // If not equal, a cost will be there        let res = 0;        for (let i = 0, j = len - 1; i < j; i++, j--)          {            if (str[i] != str[j])            {                res += Math.min(str[i].charCodeAt(), str[j].charCodeAt()) - 'a'.charCodeAt() + 1;            }        }                       return res;    }         let str = "abcdef";      document.write(cost(str));        </script>
Output :  
6
 
vt_m
Sam007
divyesh072019
palindrome
Strings
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
Different methods to reverse a string in C/C++
KMP Algorithm for Pattern Searching
Convert string to char array in C++
Array of Strings in C++ (5 Different Ways to Create)
Reverse words in a given string
Caesar Cipher in Cryptography
Length of the longest substring without repeating characters
Check whether two strings are anagram of each other