This is the third solution to check whether a string can be formed as a palindrome. This approach uses the eliminating the repeated characters from the input string using the String Buffer class.
import java.util.Scanner;
public class CheckForPalindrome {
public static void main(String[] args) {
StringBuffer targetStr=new StringBuffer("");
Scanner inpStr=new Scanner(System.in);
System.out.print("Enter an input string= ");
String strInput=inpStr.next();
/* Add each character of the string to the String Buffer,
* If same character appears again delete from the String Buffer,
* continue this process until the entire input string processed*/
for(int i=0;i<strInput.length();i++) {
int indexVal=targetStr.indexOf(String.valueOf(strInput.charAt(i)));
if (indexVal >= 0)
targetStr.deleteCharAt(indexVal);
else
targetStr.append(strInput.charAt(i));
}
/* As per the logic String Buffer must contains 0 or 1 character,
* to form the Palindrome string from the given string */
if (targetStr.length()<=1)
System.out.println("The string "+strInput+" can be rearranged as a Palindrome");
else
System.out.println("The string "+strInput+" can not be rearranged as a Palindrome");
inpStr.close();
}
}
OUTPUT:
Enter an input string= abbccaddd
The string abbccaddd can be rearranged as a Palindrome

Leave a comment