Palindrome Permutation

How can you check whether there exists a permutation P of a given string S such that P is a palindrome?
This question has been asked here https://leetcode.com/problems/palindrome-permutation/. One way to solve it is to generate all the permutations of S and check for palindrome-ness for each one - that's exponential in time.
But you can solve it in a linear pass. All you need to think about is the underlying structure of a palindrome. A palindrome can be created if and only if there exists at most one character in the string with an odd frequency count. With that rule in mind all you need to do is count the frequency of characters and perform the above check - that's it. Code is below, cheers, ACC.


public class Solution
{
    public bool CanPermutePalindrome(string s)
    {
        if (String.IsNullOrEmpty(s)) return true;
        Hashtable count = new Hashtable();
        foreach (char c in s)
        {
            if (!count.ContainsKey(c)) count.Add(c, 0);
            count[c] = (int)count[c] + 1;
        }

        int oddCount = 0;
        foreach (char key in count.Keys)
        {
            if (((int)count[key]) % 2 == 1)
            {
                oddCount++;
            }
            if (oddCount > 1)
            {
                return false;
            }
        }

        return true;
    }
}

Comments

Popular posts from this blog

Count Binary Substrings

Count Vowels Permutation: Standard DP

Maximum Number of Balloons