This is the first solution to check whether a string can be formed as a palindrome. This approach uses the core logic to check the criteria for the palindrome.
import java.util.HashMap;
import java.util.Scanner;
public class CheckStringForPalindrome {
public static void main(String[] args) {
HashMap<Character, Integer> hmCharsCount = new HashMap<Character, Integer>();
Scanner inpStr=new Scanner(System.in);
System.out.println("Enter the input string is=");
String palinStr=inpStr.nextLine();
// Use the Hash Map collection to find the count each character occurrences
for(int i=0;i<palinStr.length();i++)
if(!hmCharsCount.containsKey(palinStr.charAt(i)))
hmCharsCount.put(palinStr.charAt(i), 1);
else
hmCharsCount.put(palinStr.charAt(i), hmCharsCount.get(palinStr.charAt(i))+1);
System.out.println("The Hashmap of each character occurences are: "+hmCharsCount);
Character[] charKeys=new Character[hmCharsCount.size()];
int[] charCnts=new int[hmCharsCount.size()];
int i=0;
//Separate the Character keys and their respective counts into separate arrays
for (HashMap.Entry<Character, Integer> entry: hmCharsCount.entrySet() ) {
charKeys[i]=entry.getKey();
charCnts[i++]=entry.getValue();
}
inpStr.close();
for(i=0;i<hmCharsCount.size();i++)
System.out.println("The respective Character key="+charKeys[i]+" and number of occurances is="+charCnts[i]);
// Get the odd Character counts and even Character Counts
int oddCntOfChars=0,evnCntOfChars=0;
for (int k=0;k<charCnts.length;k++) {
if (charCnts[k]%2 == 0)
evnCntOfChars++;
else
oddCntOfChars++;
}
System.out.println("The Even count of Character keys are="+evnCntOfChars);
System.out.println("The Odd count of Character keys are="+oddCntOfChars);
/* There must be one and only one character key in the input string with odd number of times.
Any number of character keys with even number of count are allowed. Hence the, below
condition check is the eligibility criteria to form the successful Palindrome */
if (oddCntOfChars <= 1)
System.out.println("The string "+palinStr+" can be rearranged as a Palindrome");
else
System.out.println("The string "+palinStr+" can not be rearranged as a Palindrome");
}
}
OUTPUT:
Enter the input string is=
abbbccakk
The Hashmap of each character occurences are: {a=2, b=3, c=2, k=2}
The respective Character key=a and number of occurances is=2
The respective Character key=b and number of occurances is=3
The respective Character key=c and number of occurances is=2
The respective Character key=k and number of occurances is=2
The Even count of Character keys are=3
The Odd count of Character keys are=1
The string abbbccakk can be rearranged as a Palindrome

Leave a comment