This is the second 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 Hash map collection.
import java.util.HashMap;
import java.util.Scanner;
public class CheckPalindromeStr {
public static void main(String[] args) {
HashMap<Character, Integer> hmCharsCount = new HashMap<Character, Integer>();
Scanner inpStr=new Scanner(System.in);
System.out.print("Enter an input string= ");
String strInput=inpStr.next();
/* Add each character occurrence of the string to the Hash map,
* If same character appears delete it from the Hash map,
* continue this process until the entire input string processed*/
for(int i=0;i<strInput.length();i++)
if(!hmCharsCount.containsKey(strInput.charAt(i)))
hmCharsCount.put(strInput.charAt(i), 1);
else
hmCharsCount.remove(strInput.charAt(i));
/* As per the logic Hash map must contains 0 or 1 character,
* to form the palindrome string from te given string */
if (hmCharsCount.size()<=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= abbbacccc
The string abbbacccc can be rearranged as a Palindrome

Leave a comment