Remove a character from a string to make it a palindrome

Remove a character from a string to make it a palindrome
Given a string, we need to check whether it is possible to make this string a palindrome after removing exactly one character from this.
Examples:
Input  : str = “abcba”
Output : Yes
we can remove character ‘c’ to make string palindrome


Input  : str = “abcbea”
Output : Yes
we can remove character ‘e’ to make string palindrome


Input : str = “abecbea”
It is not possible to make this string palindrome

just by removing one character

PROGRAM:

public class Ma1 { public boolean palindrome(String s1,String s2){ // Palindrome function boolean b = true; StringBuilder sb = new StringBuilder(s2); String x = sb.reverse().toString(); if(!s2.equals(s1)){ b=false; } return b; } public void pal2(String s){ char[] a = s.toCharArray(); for(int i=0;i<a.length;i++){ String x = ""; char q = a[i]; a[i]='!'; //Making particular char as '!' To remove from String for(int j=0;j<a.length;j++){ if(b[j]!='!') x = x + a[j]; } System.out.println("Original String:"+x); StringBuilder sb = new StringBuilder(x); String n = sb.reverse().toString(); boolean bo; System.out.println("Reversed String:"+n); Ma1 m = new Ma1(); bo = m.palindrome(x,n); System.out.println(bo); a[i]=q; //To restore the particular in String } } public static void main(String[] args) { Ma1 m = new Ma1(); //Creating Object String s = "ABCBEA"; m.pal2(s); } }

OUTPUT:

Original String:BCBEA Reversed String:AEBCB false Original String:ACBEA Reversed String:AEBCA false Original String:ABBEA Reversed String:AEBBA false Original String:ABCEA Reversed String:AECBA false Original String:ABCBA Reversed String:ABCBA true Original String:ABCBE Reversed String:EBCBA false


Comments

Popular Posts