how can i know if a word has an anagram that’s palindrome?

So What I did is used HashMap instead of creating words from the given word
A String can be of even or odd length


If “EVEN” String is palindrome then every “character” in the String will appear even times
eg: String str = maam : m=2, a=2


If “ODD” String is a palindrome then there will only be 1 character of odd occurrence and the rest will occur even times.
eg: String str = mmaad: m=2,a=2,d=1


To store the Occurrence of the Characters in the String we will use HashMap where Character of the String is the KEY and its occurrence is VALUE

HashMap<Character,Integer> mapChar = new HashMap<>();

And we will add each Character in the HashMap with the number of times it has appeared in the String.

Now we will check if the String length is “even” or “odd” if “EVEN” Length String we know that every character will appear EVEN times and if any time a character appears “ODD” times we return false i.e It’s not a Palindrome

for (Map.Entry<Character, Integer> entries : mapChar.entrySet()) {
    if (entries.getValue() % 2 != 0) {
        return false;
    }
}

If “ODD” Length String we know that only one Character will appear odd time and the rest will be of EVEN Occurrence
And if there are 2 characters that occur odd times then its not a palindrome

// Number of times odd value Character as occurred
int occur1 = 0;
for (Map.Entry<Character, Integer> entries : mapChar.entrySet()) {
    if (entries.getValue() % 2 == 1) {
        occur1++;
        if (occur1 > 1) {
            return false;
        }
    }
}

Here’s the whole Code:

public static void main(String[] args) throws Exception {
    boolean check = isPalindromic("malayalam", "");
    System.out.println(check);
}
public static boolean isPalindromic(String word, String mark) {
    boolean isPal = true;
    if (word.length() == 0) {
        return false;
    }
    HashMap<Character, Integer> mapChar = new HashMap<>();
    for (int i = 0; i < word.length(); i++) {
        char ch = word.charAt(i);
        if (mapChar.containsKey(ch)) {
            mapChar.put(ch, mapChar.get(ch) + 1);
        } else {
            mapChar.put(ch, 1);
        }
    }
    if (word.length() % 2 == 0) {
        for (Map.Entry<Character, Integer> entries : mapChar.entrySet()) {
            if (entries.getValue() % 2 != 0) {
                return false;
            }
        }
    } else {
        int occur1 = 0;
        for (Map.Entry<Character, Integer> entries : mapChar.entrySet()) {
            if (entries.getValue() % 2 == 1) {
                occur1++;
                if (occur1 > 1) {
                    isPal = false;
                    break;
                }
            }
        }
    }
    return isPal;
}

output:

mmaa
Is Palindrome: true
mmaad
Is Palindrome: true
niti
Is Palindrome: false

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top