266. Palindrome Permutation

问题描述:

Given a string, determine if a permutation of the string could form a palindrome.

Example 1:

Input: "code"
Output: false

Example 2:

Input: "aab"
Output: true

Example 3:

Input: "carerac"
Output: true

解题思路:

首先考虑corner cases:s为空,空字符串也是一个有效的回文,所以应返回true。

可以对字符串中出现的字符个数进行统计:有一个或0个字符出现的次数为奇数时,可以构成回文,因为有一个可以放到中心。

其他则不可以

代码:

class Solution {
public:
    bool canPermutePalindrome(string s) {
        unordered_map<char, int> m;
        for(char c : s){
            m[c]++;
        }
        int oddCnt = 0;
        for(auto p : m){
            if(p.second%2 == 1) oddCnt++;
        }
        return oddCnt < 2;
    }
};