Given a string, determine if a permutation of the string could form a palindrome.
Input: "code"
Output: false
Input: "aab"
Output: true
Input: "carerac"
Output: true
bool canPermutePalindrome(string s) { // time: O(n); space: O(1)
if (s.empty()) return false;
vector<int> record(128, 0);
for (char c : s) ++record[c];
int odd = 0;
for (int num : record) {
if (num & 1) ++odd;
if (odd > 1) return false;
}
return true;
}
bool canPermutePalindrome(string s) { // time: O(n); space: O(1)
unordered_set<char> hashset;
for (char c : s) {
if (!hashset.count(c)) hashset.insert(c);
else hashset.erase(c);
}
return hashset.size() <= 1;
}