-1

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.

Marian Ene
  • 615
  • 2
  • 7
  • 21
  • 4
    Could you give some examples of what you mean? For example, is "abcabc" valid, in that it's an anagram of "abccba" even though neither of them are real words? – Jon Skeet Mar 26 '15 at 17:36
  • i.e. "naa" is the anagram of "ana" palindrome – Marian Ene Mar 26 '15 at 17:41
  • Why would need to get the HashCode for every character and not use the character itself? – Saggio Mar 26 '15 at 17:42
  • 1
    Right, so it doesn't matter whether or not they're really words? That sounds like the check is just "at most one letter occurs an odd number of times". – Jon Skeet Mar 26 '15 at 17:42

2 Answers2

6

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;
}
petelids
  • 12,305
  • 3
  • 47
  • 57
0

Saved char in a dictionary as key, then check if more than one key is odd. this way also have all unique char ready to make anagram.

 var length = s.Length;

        if (length == 0) return false;

        var dic = new Dictionary<char, int>();

        for (var i = 0; i < length; i++)
        {

            if (dic.ContainsKey(s[i]))
            {
                dic[s[i]]++;
                continue;
            }

            dic.Add(s[i], 1);
        }
        int odd = 0;
        foreach (var pv in dic)
        {
            if (odd > 1) return false;
            if (pv.Value % 2 == 0)
            {
                continue;
            }
            odd++;
        }
seagull
  • 237
  • 1
  • 7
  • 19