Thursday, February 11, 2016

266. Palindrome Permutation

Question:

Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code" -> False, "aab" -> True, "carerac" -> True.

Hint:
  1. Consider the palindromes of odd vs even length. What difference do you notice?
  2. Count the frequency of each character.
  3. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?
Solution:(HashTable)

S="aab", whose length is odd number.
a-->2
b-->1
S="aabd",whose length is even number.
a-->2
b-->1
d-->1
O(n).

Code(C++):
class Solution {
public:
    bool canPermutePalindrome(string s) {
        unordered_map hashTable;
        int odd = 0;
        for(auto ch:s){
            hashTable[ch]++;
            if(hashTable[ch]%2==1) odd++;
            else odd--;
        }
               return odd<2;
    }
};

No comments :

Post a Comment