Search code examples
c#palindromeanagram

Check if string is anagram of palindrome


My question is: How do you check if a given string is the anagram of a palindrome?

I found some solutions in Python on the internet, but I'm not sure how can I check this yet. I was thinking about converting the strig to a char [], and then get the HashCode for every character, but I'm stuck.


Solution

  • If you're not interested in the palindrome or anagram being a real word then I think you can reframe the problem as check if a given string has no more than one character that appears an uneven number of times. This is on the basis that only the middle character can possibly occur an odd number of times. As long as that is satisfied then you can form a palindrome from the string.

    To do that you can use Linq. Something like this perhaps:

    private static bool IsPalindromeAnagram(string test)
    {
        var charCount = test.GroupBy(c => c, (c, i) => new
            {
                character = c,
                count = i.Count()
            });
    
        return charCount.Count(c => c.count % 2 == 1) <= 1;
    }