Convert the string into palindrome string by changing only one character
Last Updated :
18 Jul, 2022
Given a string str. Check if it is possible to convert the string into palindrome string by changing only one character.
Examples:
Input : str = "abccaa"
Output : Yes
We can change the second last character
i.e. 'a' to 'b' to make it palindrome string
Input : str = "abbcca"
Output : No
We can not convert the string into palindrome
string by changing only one character.
Approach : The idea is simple, we check character str[i] with str[n-i-1]. If there is a mismatch, we increment count. If count of mismatches exceed 1, we return false. Else we return true.
Below is the implementation of above idea :
C++
#include<bits/stdc++.h>
using namespace std;
bool checkPalindrome(string str){
int n = str.length();
int count = 0;
for ( int i = 0; i < n/2; ++i)
if (str[i] != str[n - i - 1])
++count;
return (count <= 1);
}
int main()
{
string str = "abccaa" ;
if (checkPalindrome(str))
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
static boolean checkPalindrome(String str){
int n = str.length();
int count = 0 ;
for ( int i = 0 ; i < n/ 2 ; ++i)
if (str.charAt(i) != str.charAt(n - i - 1 ))
++count;
return (count <= 1 );
}
public static void main(String[] args) {
String str = "abccaa" ;
if (checkPalindrome(str))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def checkPalindrome( str ) :
n = len ( str )
count = 0
for i in range ( 0 , int (n / 2 )) :
if ( str [i] ! = str [n - i - 1 ]) :
count = count + 1
if (count < = 1 ) :
return True
else :
return False
str = "abccaa"
if (checkPalindrome( str )) :
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
static bool checkPalindrome( string str){
int n = str.Length;
int count = 0;
for ( int i = 0; i < n / 2; ++i)
if (str[i] != str[n - i - 1])
++count;
return (count <= 1);
}
public static void Main()
{
string str = "abccaa" ;
if (checkPalindrome(str))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
function checkPalindrome( $str )
{
$n = strlen ( $str );
$count = 0;
for ( $i = 0; $i < $n /2; ++ $i )
if ( $str [ $i ] != $str [ $n - $i - 1])
++ $count ;
return ( $count <= 1);
}
{
$str = "abccaa" ;
if (checkPalindrome( $str ))
echo "Yes" ;
else
echo "No" ;
return 0;
}
?>
|
Javascript
<script>
function checkPalindrome(str){
let n = str.length;
let count = 0;
for (let i = 0; i < parseInt(n/2, 10); ++i)
if (str[i] != str[n - i - 1])
++count;
return (count <= 1);
}
let str = "abccaa" ;
if (checkPalindrome(str))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Output:
Yes
Time Complexity : O(n/2) , where n is size of given string.
Auxiliary Space : O(1) , as we are not using any extra space.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...