Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code"
-> False, "aab"
-> True, "carerac"
-> True.Hint:
- Consider the palindromes of odd vs even length. What difference do you notice?
- Count the frequency of each character.
- If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?
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_maphashTable; 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