Minimum reduce operations to convert a given string into a palindrome
Given a String find the minimum number of reduce operations required to convert a given string into a palindrome. In a reduce operation, we can change character to a immediate lower value. For example b can be converted to a.
Examples :
Input : abcd
Output : 4
We need to reduce c once
and d three times.
Input : ccc
Output : 0
The idea is simple. We traverse string from left and compare characters of left half with their corresponding characters in right half. We add difference between to characters to result.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int countReduce(string& str)
{
int n = str.length();
int res = 0;
for ( int i = 0; i < n / 2; i++)
res += abs (str[i] - str[n - i - 1]);
return res;
}
int main()
{
string str = "abcd" ;
cout << countReduce(str);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int countReduce(String str)
{
int n = str.length();
int res = 0 ;
for ( int i = 0 ; i < n / 2 ; i++)
res += Math.abs(str.charAt(i)
- str.charAt(n - i - 1 ));
return res;
}
public static void main (String[] args)
{
String str = "abcd" ;
System.out.println( countReduce(str));
}
}
|
Python3
def countReduce( str ):
n = len ( str )
res = 0
for i in range ( 0 , int (n / 2 )):
res + = abs ( int ( ord ( str [i])) -
int ( ord ( str [n - i - 1 ])) )
return res
str = "abcd"
print (countReduce( str ))
|
C#
using System;
class GFG {
static int countReduce( string str)
{
int n = str.Length;
int res = 0;
for ( int i = 0; i < n / 2; i++)
res += Math.Abs(str[i]
- str[n - i - 1]);
return res;
}
public static void Main ()
{
string str = "abcd" ;
Console.WriteLine( countReduce(str));
}
}
|
PHP
<?php
function countReduce( $str )
{
$n = strlen ( $str );
$res = 0;
for ( $i = 0; $i < $n / 2; $i ++)
$res += abs (ord( $str [ $i ]) -
ord( $str [( $n - $i - 1)]));
return $res ;
}
$str = "abcd" ;
echo countReduce( $str );
?>
|
Javascript
<script>
function countReduce(str)
{
let n = str.length;
let res = 0;
for (let i = 0; i < parseInt(n / 2, 10); i++)
res += Math.abs(str[i].charCodeAt() - str[n - i - 1].charCodeAt());
return res;
}
let str = "abcd" ;
document.write(countReduce(str));
</script>
|
Time Complexity: O(n) where n is the length of the string
Auxiliary Space: O(1)
Last Updated :
02 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...