266. Palindrome Permutation (Easy)

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:

class Solution {
public:
    bool canPermutePalindrome(string s) {
        unordered_map<char, int> m;
        for (auto& a: s) {
            ++m[a];
        }
        bool can = true;
        for (auto& a: m) {
            if (a.second % 2) {
                if (can) can = false;
                else return false;
            }
        }
        return true;
    }
};

results matching ""

    No results matching ""