Thursday, April 30, 2015

Anagram of palindrome

Write a function:
    class Solution { public int isAnagramOfPalindrome(String S); }
    that, given a non-empty string S consisting of N characters, returns 1 if S is an anagram of some palindrome and returns 0 otherwise. Analysis: If a string is an anagram of a palindrome, each letter must appear even times, or only one letter appears odd time(s), the others appear even times.
bool isAnagramOfPalindrome(const char *s)
{
    long res = 0;
    while(*s) res ^= i<<(*s - 'A');
    return !(res&(res-1))
}
!(res&(res-1)) means either its 0 or only one of its bits is 1.