LeetCode 266. Palindrome Permutation

This problem currently has a lock..... 大哭

Search it on Google then.....大笑

Problem:

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

For example,
"code" -> False, "aab" -> True, "carerac" -> True.


#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;

// Given a string, determine if a permutation of the string could form a palindrome.
// Think: if the string can form a palindrome, it can either has length 1/0 or
// The frequency of the indivial characters should be even with at most 1 exception.

bool canPermutePalindrome(string s) {
    if(s.size() <= 1) return true;
    unordered_map<char, int> charToCount;
    for(int i = 0; i < s.size(); ++i) {
        auto iter = charToCount.find(s[i]);
        if(iter == charToCount.end()) {
            charToCount.insert({s[i], 1});
        } else {
            iter->second++;
        }
    }
    int count = 0;
    for(auto iter = charToCount.begin(); iter != charToCount.end(); ++iter) {
        if(iter->second % 2) count++;
    }
    return count <= 1;
}

int main(void) {
    cout << canPermutePalindrome("abc") << endl;
    cout << canPermutePalindrome("aab") << endl;
}


你可能感兴趣的:(LeetCode 266. Palindrome Permutation)